I'm trying to link the output of C++ using ld and not g++. I'm only doing this to learn how to do it, not for practical purposes, so please don't suggest just to do it with g++.
Looking at this question, the person gets the same error when they run the ld command:
$ ld test.o -o test.out
ld: warning: cannot find entry symbol _start; defaulting to 00000000004000e8
test.o: In function `main':
test.cpp:(.text+0x1c): undefined reference to `strcasecmp'
test.cpp:(.text+0x23): undefined reference to `std::cout'
test.cpp:(.text+0x28): undefined reference to `std::ostream::operator<<(int)'
test.cpp:(.text+0x2d): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
test.cpp:(.text+0x35): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
test.o: In function `__static_initialization_and_destruction_0(int, int)':
test.cpp:(.text+0x75): undefined reference to `std::ios_base::Init::Init()'
test.cpp:(.text+0x7a): undefined reference to `__dso_handle'
test.cpp:(.text+0x84): undefined reference to `std::ios_base::Init::~Init()'
test.cpp:(.text+0x89): undefined reference to `__cxa_atexit'
ld: test.out: hidden symbol `__dso_handle' isn't defined
ld: final link failed: Bad value
The answers in the linked post suggest that adding the C++ library as a linker argument will fix the problem, so I tried
ld test.o -o test.out -llibstd++
which is what they suggested, and I also tried a lot of other library names like libstdc++ or stdc++. But I'll always get an error that looks like
ld: cannot find -llibstd++
What am I doing wrong and how can I link my object files using ld?
If you run
g++
with the-v
flag, you'll see the link line it uses. Here's a simple example program:And the output from running
g++ -v -o example example.cpp
:Wow, what a mess. Conveniently the link line is the last one there, so you can see what's happening pretty easily.
As you noticed in your comment below, the front-end is using
collect2
rather thanld
. Luckily,collect2
is just an alias forld
. Here's an example using it:First let's generate an object file:
Then we'll use the front-end to link it to see the link line:
Then throw away the binary, and link ourselves (normally, I would have just copy/pasted the line, but to make it easier to read I did it the multiline way with
\
s):Finally, run it!
You can probably significantly shorten that link line by removing some arguments. Here's the minimal set I came up with after some experimentation:
This set of flags and libraries will of course depend on what library functions and language features your program uses.