Nullptr
Nullptr

Reputation: 3183

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

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?

Upvotes: 2

Views: 6555

Answers (4)

S.S. Anne
S.S. Anne

Reputation: 15566

Link with -lgcc if you need to use ld. Otherwise, use g++ to link.

Upvotes: 0

tsaeger
tsaeger

Reputation: 96

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

Upvotes: 6

Cheers and hth. - Alf
Cheers and hth. - Alf

Reputation: 145204

use g++ to invoke the linker, like

g++ test.o -o test.exe

Cheers & hth.,

Upvotes: 1

Cat Plus Plus
Cat Plus Plus

Reputation: 129754

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

Upvotes: 1

Related Questions