c++变量的多重定义,即使使用extern
c++ multiple definition of variable even with extern
我一直在尝试修复我的多重定义错误,大多数答案似乎是使用extern,但即使在我这样做之后,错误仍然存在
main.cpp
#include "header.h"
int main(){
ifstream indata;
indata.open(file.c_str());
int x;
while(indata){
indata >> x;
print(x);
}
return 0;
}
函数.cpp
#include "header.h"
void print(int x){
cout << x << endl;
}
header.h
#ifndef _HEADER_H
#define _HEADER_H
#include <fstream>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
extern string file="testFile.txt";
void print(int x);
#endif
Makefile
all: main
main.o: main.cpp header.h
g++ -c main.cpp
functions.o: functions.cpp header.h
g++ -c functions.cpp
main: main.o functions.o
g++ main.o functions.o -o main
check: all
./main
clean:
rm -f *.o main
我得到的错误信息是
make
g++ -c main.cpp
In file included from main.cpp:1:0:
header.h:11:15: warning: ‘file’ initialized and declared ‘extern’
extern string file="testFile.txt";
^
g++ -c functions.cpp
In file included from functions.cpp:1:0:
header.h:11:15: warning: ‘file’ initialized and declared ‘extern’
extern string file="testFile.txt";
^
g++ main.o functions.o -o main
functions.o:functions.cpp:(.bss+0x0): multiple definition of `file'
main.o:main.cpp:(.bss+0x0): first defined here
collect2: error: ld returned 1 exit status
Makefile:10: recipe for target 'main' failed
make: *** [main] Error 1
有人能在这里给我指正确的方向吗。
外部声明是要显示给每个翻译单元的声明,而不是定义,
考虑只留下
extern string file;
在标题中,然后将定义移动到其中一个源文件:
string file = "testFile.txt";
您的初始值设定项"重写"extern
关键字,使行成为定义而非声明。
你不能既有蛋糕又吃。
- https://stackoverflow.com/a/30803988/560648
在header.h:中声明
extern string file;
并在.cpp文件中定义它:
string file = "testFile.txt";
否则,包括header.h的所有内容都将有自己的file
定义,从而导致出现"file'的多重定义"错误。
Extern是一个指令,用于告诉链接器符号的定义在另一个对象文件中可用。extern是一个声明说明符,即它不是一个定义。不应定义声明为extern的变量。
按照惯例,在头文件中定义全局变量是不好的。这就是多重定义错误的原因。这是因为您的头文件包含在两个cpp文件中。
解决方案:
从收割台上拆下。hextern string file="testFile.txt"
添加到functions.cppstring file="testFile.txt"
添加到main.cppextern声明extern字符串文件;
相关文章:
- 是否可以在不使用 decltype 的情况下推断先前定义的 extern 变量的类型
- "extern"声明以及带有和不带参数列表的类模板实例的后续定义
- 有什么方法可以在标头中定义和声明 extern 对象吗?
- 在另一个文件中初始化的 extern 数组中未定义的引用
- 如何使 extern 方法在共享库中定义,但使用 cmake 在其他目标中声明?
- 是否应该在只有定义的文件中使用 extern "C"?
- 为什么我不能在标头中只定义一个非常量 gloabal 变量?如果我使用命名空间,为什么我必须声明它"extern"?
- 我应该在源文件之间共享的常量的定义中添加关键字"extern"吗
- 在 c++ 对象上使用 extern 时未定义引用,但不是整型
- C4211:使用了非标准扩展:将extern重新定义为static
- 为什么C++编译器允许 extern 关键字与定义相结合
- 在 main() 与全局中定义 extern 变量
- Eclipse/GCC:对 Extern 变量的未定义引用
- 使用 extern 引用在不同编译单元中定义的函数
- 当使用extern在文件之间共享常量时,为什么定义中需要extern
- 具有最小"extern"使用测试用例的未定义引用问题
- 在.so内部定义的extern变量和可执行引线执行未定义的行为
- c++变量的多重定义,即使使用extern
- NDK 未定义对 {extern "C" function} 的引用?
- 后期绑定到具有"extern"定义变量的库