Link error while using MinGW compiler (can't find __main)

别等时光非礼了梦想. 提交于 2019-12-24 04:37:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!