I'm writing a C++ program where each file has it's own set of global variable declarations. Most of these files make use of global variables that were defined in the other files using extern.
Here's an example similar to my program:
Main.cpp
#include "stdafx.h"
#include <iostream>
#include "Other_File.cpp"
int var1;
int var2;
int main()
{
var1 = 1;
var2 = 2;
otherFunction();
var4 = 4; // From Other_File.cpp
std::cout << var1 << " " << var2 << " " << var3 << " " << var4 << std::endl;
return(0);
}
Other_File.cpp
extern int var1;
extern int var2;
int var3;
int var4;
void otherFunction()
{
var3 = var1 + var2;
var4 = 0;
}
When I build this code in Visual Studio (Windows), everything runs fine and the output is correct. But when I attempt to build using g++ on Linux I receive the following error:
g++ -o Testing Testing.o Other_File.o Other_File.o:(.bss+0x0): multiple definition of
var3' Testing.o:(.bss+0x0): first defined here Other_File.o:(.bss+0x4): multiple definition of
var4' Testing.o:(.bss+0x4): first defined here Other_File.o: In functionotherFunction()': Other_File.cpp:(.text+0x0): multiple definition of
otherFunction()' Testing.o:Testing.cpp:(.text+0x0): first defined here collect2: ld returned 1 exit status make: *** [Testing] Error 1
Is this because I'm "including" the other file in my main file?
If not what's the issue with my code?
Edit: This is the content of my Makefile for g++:
Testing: Testing.o Other_File.o
g++ -o Testing Testing.o Other_File.o
Testing.o: Testing.cpp
g++ -c -std=c++0x Testing.cpp
Other_File.o: Other_File.cpp
g++ -c -std=c++0x Other_File.cpp
clean:
rm *.o Calculator
See Question&Answers more detail:os