加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 编译单元之间共享的全局const对象

发布时间:2020-12-16 07:49:31 所属栏目:百科 来源:网络整理
导读:当我声明并初始化一个const对象时. // ConstClass.hclass ConstClass{};const ConstClass g_Const; 两个cpp文件包含此标头. // Unit1.cpp#include "ConstClass.h"#include "stdio.h"void PrintInUnit1( ){ printf( "g_Const in Unit1 is %d.rn",g_Const );
当我声明并初始化一个const对象时.
// ConstClass.h
class ConstClass
{
};

const ConstClass g_Const;

两个cpp文件包含此标头.

// Unit1.cpp
#include "ConstClass.h"
#include "stdio.h"

void PrintInUnit1( )
{
    printf( "g_Const in Unit1 is %d.rn",&g_Const );
}

// Unit2.cpp
#include "ConstClass.h"
#include "stdio.h"

void PrintInUnit2( )
{
    printf( "g_Const in Unit2 is %d.rn",&g_Const );
}

当我构建解决方案时,没有链接错误,你会得到什么如果g_Const是一个非const基本类型!

PrintInUnit1()和PrintInUnit2()表明在两个编译单元中有两个独立的“g_Const”具有不同的地址,为什么?

==============

我知道如何修复它.(使用extern关键字进行声明,并在一个cpp文件中定义它.)

我想知道为什么我在这个示例中没有得到redfined链接错误.

解决方法

https://stackoverflow.com/a/6173889/1508519

const variable at namespace scope has internal linkage. So they’re
basically two different variables. There is no redefinition.

3.5/3 [basic.link]:

A name having namespace scope (3.3.5) has internal linkage if it is
the name of

— an object,reference,function or function template that is
explicitly declared static or,

— an object or reference that is explicitly declared const and neither
explicitly declared extern nor previously declared to have external
linkage; or

— a data member of an anonymous union.

如果您希望它具有外部链接,请使用extern.

如另一个答案所述,头文件只是粘贴在cpp文件中.两个cpp文件中都包含相同的头文件,但它们是单独的转换单元.这意味着变量的一个实例与另一个实例不同.另一方面,让编译器知道您已在其他地方定义了变量,请使用extern关键字.这确保了翻译单元之间只共享一个实例.然而,extern const Test测试只是一个声明.你需要一个定义.只要在某个cpp文件中定义了一次就定义它并不重要.您可以根据需要多次声明它(这样可以方便地将其放在头文件中.)

例如:

Constant.h

class Test
{
};

extern const Test test;

Unit1.cpp

#include "Constant.h"
#include <iostream>

void print_one()
{ std::cout << &test << std::endl; }

Unit2.cpp

#include "Constant.h"
#include <iostream>

void print_two()
{ std::cout << &test << std::endl; }

main.cpp中

extern void print_one();
extern void print_two();

int main()
{
   print_one();
   print_two();
}

Constant.cpp

#include "Constant.h"
const Test test = Test();

Makefile文件

.PHONY: all
all:
   g++ -std=c++11 -o test Constant.cpp Unit1.cpp Unit2.cpp main.cpp

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读