c++变量的多重定义,即使使用extern

c++ multiple definition of variable even with extern

本文关键字:extern 定义 变量 c++      更新时间:2023-10-16

我一直在尝试修复我的多重定义错误,大多数答案似乎是使用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字符串文件;