Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ multiple definition of variable even with extern

Tags:

c++

I've been trying to fix my multiple definition error and most answers seem to be to use extern but even after I did that the error still persists

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

and the resulting error message i get is

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

Can someone point me in the right direction here.

like image 504
Jc.kal Avatar asked Dec 19 '22 22:12

Jc.kal


2 Answers

An extern declaration is the one to be shown to every translation unit, not a definition,

Consider leave nothing but

extern string file;

in the header, then move the definition to one of the source files:

string file = "testFile.txt";
like image 113
iDingDong Avatar answered Dec 24 '22 01:12

iDingDong


Your initializer "overrides" the extern keyword, making the line a definition rather than a declaration.

You cannot have your cake and eat it too.

  • https://stackoverflow.com/a/30803988/560648
like image 25
Lightness Races in Orbit Avatar answered Dec 24 '22 02:12

Lightness Races in Orbit