编译器:vs2019
对于普通的全局变量的链接性为外部的,也就是说,如下的代码编译是不会通过的,因为有重定义
//file1.cpp
#include<iostream>
using namespace std;
int test_a;
int main() {
cout << test_a << endl;
system("pause");
return 0;
}
//file2.h
#ifndef TEST_H
#define TEST_H
int test_a = 10;
#endif // !1
此时编译会报错,因为在程序进入链接阶段的时候,发现找到了多个test_a的定义,解决方法是,在file1.cpp中改为extern int test_a,或者是把两个函数中的定义都改成static将链接性改为内部,只能在本文件生效
但是对于const类型的变量来说,其链接性为内部,见如下代码
因为链接性为内部,所以不会报错,这两个变量只在单个文件中生效
//file1.cpp
#include<iostream>
using namespace std;
const int test_a = 10;
int main() {
cout << test_a << endl;
system("pause");
return 0;
}
//file2.h
#ifndef TEST_H
#define TEST_H
const int test_a = 20;
#endif // !1