问题描述
我只是构建一个简单的C ++项目.代码如下所示:
-------- head.h --------
#ifndef _HEAD_H_#定义_HEAD_H_int my_var = 100;#万一
-------- src1.cpp --------
#include"head.h"
-------- src2.cpp --------
#include"head.h"int main(){返回0;}
然后用这些命令构建二进制文件:
g ++ -c src1.cpp -o scr1.og ++ -c src2.cpp -o src2.og ++ -o a.out src2.o src1.o
但是它在链接步骤中失败,并告诉我我有"my_var"的多个定义.我不只是在头文件中使用安全保护宏吗?我不明白.有人知道为什么吗?>
谢谢.
ps:如果我将my_var定义为静态变量,则代码可以通过链接.我也不明白.
按以下方式更改标题
#ifndef _HEAD_H_#定义_HEAD_H_extern int my_var;#万一
例如在主模块中添加行
#include"head.h"int my_var = 100;int main(){返回0;}
问题在于,由于标头包含在两个模块中,因此每个模块都包含一个具有外部链接的变量,其名称与其他模块中的变量相同.而且链接器不知道要使用哪个变量.
I just build a simple C++ project. The codes are shown in the follows:
-------- head.h --------
#ifndef _HEAD_H_
#define _HEAD_H_
int my_var = 100;
#endif
-------- src1.cpp --------
#include "head.h"
-------- src2.cpp --------
#include "head.h"
int main() { return 0; }
And I build the binary with those command:
g++ -c src1.cpp -o scr1.o
g++ -c src2.cpp -o src2.o
g++ -o a.out src2.o src1.o
But it fails in the linking step and tells me that i have "multiple definition of `my_var'. Did't I just use safe guard macros in the head file? I don't understand. Anyone know why?
thanks.
ps:If I define my_var as a static variable, then the code can pass linking. I don't understand it either.
Change the header the following way
#ifndef _HEAD_H_
#define _HEAD_H_
extern int my_var;
#endif
And for example add line in the module with main
#include "head.h"
int my_var = 100;
int main() { return 0; }
The problem is that as the header is included in two modules then each module contains a variable with external linkage with the same name as a variable in other module. And the linker does not know which variable to use.
这篇关于多个,包括带有可变定义的头文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!