C++ 内部链接性之const

一、原理分析

假设将常量放在头文件中,并在同一个程序的多个文件中使用该头文件,
如果全局 const 声明的链接性像常规变量那样是外部的,则根据单定 义规则,这将出错。然而,在头文件中const修饰的全局变量,被多个文件包含,并不会报错,因此,可以发现,const修饰的全局变量的链接性为内部的。
结论:在默认情况下全局变量的链接性为外部的,但const全局变量的链接性为内部的。
二、示例代码
test.sh
#ifndef TEST_H
#define TEST_H
const int num =3;//const修饰的全局变量num,链接性为内部的,效果等同于static,因此该头文件可以在多                    
                 //个文件中引用,否则将报错

#endif 

file1.cpp

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


void remote_access();
using namespace std;

int main()
{

    cout<<"main() num="<<num<<endl;
    remote_access();
 
    return 0;
}

file2.cpp

#include <iostream>

#include "test.h"

 void remote_access()

{

    using namespace std;

    cout<<"remote_access() num="<<num<<endl;

}

编译以上两个文件:

g++ file1.cpp file2.cpp -o filetest

猜你喜欢

转载自blog.csdn.net/banzhuantuqiang/article/details/130938290
今日推荐