我一直在試圖解決我的多重定義錯誤,最答案似乎是爲extern使用,但即使我做了錯誤仍然存在C++多重定義,即使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;
}
functions.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
有人能指出我朝着正確的方向。
無關的問題,但不包括在報頭的命名空間('使用命名空間x')更多信息:HTTP://。 stackoverflow.com/questions/4872373/why-is-including-using-namespace-into-a-header-file-a-bad-idea-in-c – Unimportant
http://stackoverflow.com/a/30803988/560648 –