Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MinGW undefined reference to malloc, free, sprintf, _beginthreadex

Tags:

c

build

mingw

ld

I'm using MinGW. I have some code which calls malloc and a few other general purpose functions. When I type:

gcc TestCode.c

I get an a.exe file, it works perfect, and I don't get any warnings.

If I type this:

gcc -c TestCode.c -o TestCode.o
ld *.o

I get a whole bunch of warnings such as:

TestCode.o:TestCode.c:(.text+0xa): undefined reference to `__main'
TestCode.o:TestCode:(.text+0x2e): undefined reference to `printf'
TestCode.o:TestCode:(.text+0x42): undefined reference to `_strerror'
TestCode.o:TestCode:(.text+0x69): undefined reference to `snprintf'
TestCode.o:TestCode:(.text+0x7e): undefined reference to `malloc'
TestCode.o:TestCode:(.text+0x93): undefined reference to `_strerror'
TestCode.o:TestCode:(.text+0xb1): undefined reference to `sprintf'
TestCode.o:TestCode:(.text+0xcf): undefined reference to `free'

I'm assuming this is an issue with how I'm calling the linker. As such, I'll only post the code if it isn't clear what the problem is. I'm hoping this is an easy fix and that I simply forgot to include some super obvious library when linking.

like image 877
Brett Avatar asked Mar 14 '12 03:03

Brett


2 Answers

It appears that your ld doesn't link any libraries by default. From your error messages, it looks like you need at least the C runtime and libc. Use gcc to link to get some handy defaults linked in for you:

gcc -c TestCode.c -o TestCode.o
gcc *.o

If you really want to use ld directly, you're going to need to figure out the names of your C runtime library and libc. For example (assuming libraries named libcrt and libc):

ld *.o -lcrt -lc
like image 102
Carl Norum Avatar answered Oct 15 '22 09:10

Carl Norum


As Carl Norum said, you can pass object files to gcc and it'll know it doesn't need to compile them - it just passes them on to the linker (whether or not you're compiling other source files in the same invocation).

And you should probably do that because there's a fair amount of detail that goes into linking in the CRT and windows support libraries (unless you have a very specific need to not use the default runtime). My current MinGW setup links in the following items along with my object files:

crt2.o
crtbegin.o

-ladvapi32 
-lshell32 
-luser32 
-lkernel32 
-lmingw32 
-lgcc 
-lmoldname 
-lmingwex 
-lmsvcrt 

crtend.o

Use the --verbose option to see how gcc links for you.

like image 26
Michael Burr Avatar answered Oct 15 '22 10:10

Michael Burr