compilation - Multiple definitions error in C++ -
i'm writing c++ program each file has it's own set of global variable declarations. of these files make use of global variables defined in other files using extern.
here's example similar 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; // 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 build code in visual studio (windows), runs fine , output correct. when attempt build using g++ on linux receive 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 because i'm "including" other file in main file?
if not what's issue code?
edit: content of makefile 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
don't #include
source file source file. there times , places when okay, in less 0.001% of programs needed.
what should create header file contains declarations of things needed in both source files.
then code this:
main.cpp
source file#include "stdafx.h" #include <iostream> #include "other_file.h" // note inclusion of header file here int var1; int var2; int main() { var1 = 1; var2 = 2; otherfunction(); var4 = 4; // other_file.cpp std::cout << var1 << " " << var2 << " " << var3 << " " << var4 << std::endl; }
other_file.cpp
source file, have nowother_file.h
header file, new file#pragma once // declare variables, compiler knows exist somewhere extern int var3; extern int var4; // forward declaration of function prototype void otherfunction();
both source files compiled separately , linked form final executable. linking step build fails. notice variables defined in other_source.cpp
defined in object file created source file, since include main.cpp
source file object file created source file well.
this why need learn translation units, compiler see. c++ source file goes through many phases of translation, each 1 doing own special part. translation unit single source file headers included.
this reason learn preprocessor #include
directive does. inserts included file, is, source file being preprocessed. #include
directive was, after preprocessing contents of included file, , compiler see.