mjfred mjfred -4 years ago 117
C++ Question

"Duplicate symbol" when attempting to compile two .cpp files (from XCode) in terminal (MacOSX)

I have two .cpp files, main.cpp and secondFile.cpp:

#include <iostream>

int main()
{
std::cout << "Hello, World!\n" << std::endl;
std::cout << "I was also able to add this line!" << std::endl;
return 0;
}


And

#include <iostream>

int main()
{
std::cout << "This was from the second file!" << std::endl;
return 0;
}


I have successfully run
g++ -o main.cpp main
and
g++ -o secondFile.cpp secondFile
, as well as run each of their corresponding executables. However when I attempt to compile them simultaneously into a single executable
g++ -o main.cpp secondFile.cpp bothScripts
or
clang++ main.cpp secondFile.cpp -o bothScripts
I receive the following error:

"duplicate symbol _main in:
/var/folders/49/38grlkzs44zcth3v_dw9m9dm0000gn/T/main-d43536.o
/var/folders/49/38grlkzs44zcth3v_dw9m9dm0000gn/T/secondfile-2bee63.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)"

Clearly something is being loaded twice, but I am unsure whether this is a library (iostream), that I've named both sections 'main', or something else entirely. There are certainly questions similar to this already, but many are convoluted and not as fundamental for new C++ members (hence my question here).

Context: My rationale is to practice building executables from multiple .cpp files. Is there a better way to go about this? (New to C++ but not to programming/code as a whole.)

Answer Source

The reason for your error is simple. You have 2 main() functions. As you should know, in a C++ program, the function main() generally defines the entry point of a program. When each of the files are compiled together, and have their own main() function, the compiler gets confused and throws an error. To solve this, simply change the name of the main() function in one file, and call it from the other file, if you are planning to run them together.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download