问题
I'm trying to compile a very simple program with MinGW on Windows, but I still got link errors. The program to be compiled is just C++ hello world.
Z:\dev>type test.cpp
#include <iostream>
int main() {
std::cout << "Hello World!\n";
return 0;
}
Of course, just using MinGW's g++ is okay.
Z:\dev>g++ test.cpp -o test.exe
Z:\dev>test.exe
Hello World!
However, I tried to separate compilation and linking, but failed.
Z:\dev>g++ -c test.cpp -o test.o
Z:\dev>ld test.o -o test.exe
test.o:test.cpp:(.text+0xa): undefined reference to `__main'
test.o:test.cpp:(.text+0x19): undefined reference to `std::cout'
test.o:test.cpp:(.text+0x1e): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& s
<std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
test.o:test.cpp:(.text+0x37): undefined reference to `std::ios_base::Init::~Init()'
test.o:test.cpp:(.text+0x5a): undefined reference to `std::ios_base::Init::Init()'
test.o:test.cpp:(.text+0x66): undefined reference to `atexit'
It is obvious that I've missed some libraries. So, I tried to link with several MinGW's libraries, but still no good such as -lmsvcrt
. I also did lstdc++
, but still __main
cannot be found and tons of warning messages.
Could you help me out which libraries should be linked together?
回答1:
Instead of using ld
, try using g++
to link.
Try this:
Z:\dev> g++ -c test.cpp -o test.o
Z:\dev> g++ -o test.exe test.o
回答2:
Don't call ld
directly unless you know you need it. g++
will know how to call it properly.
g++ -o test.exe test.o
回答3:
use g++
to invoke the linker, like
g++ test.o -o test.exe
Cheers & hth.,
回答4:
Link with -lgcc
if you need to use ld
. Otherwise, use g++
to link.
来源:https://stackoverflow.com/questions/4981826/link-error-while-using-mingw-compiler-cant-find-main