我一直在尝试修复我的多定义错误,大多数答案似乎是使用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;
}
Run Code Online (Sandbox Code Playgroud)
functions.cpp
#include "header.h"
void print(int x){
cout << x << endl;
}
Run Code Online (Sandbox Code Playgroud)
头文件
#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
Run Code Online (Sandbox Code Playgroud)
生成文件
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
Run Code Online (Sandbox Code Playgroud)
而我得到的错误消息是
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
Run Code Online (Sandbox Code Playgroud)
有人可以在这里指出我正确的方向。
外部声明是要显示给每个翻译单元的声明,而不是定义,
考虑别无选择
extern string file;
Run Code Online (Sandbox Code Playgroud)
在标题中,然后将定义移至源文件之一:
string file = "testFile.txt";
Run Code Online (Sandbox Code Playgroud)
在 header.h 中声明它:
extern string file;
Run Code Online (Sandbox Code Playgroud)
并在 .cpp 文件中定义它:
string file = "testFile.txt";
Run Code Online (Sandbox Code Playgroud)
否则,包含 header.h 的所有内容都将具有自己的定义file,从而导致出现“‘文件’的多重定义”错误。