MinGW未定义对malloc,free,sprintf,_beginthreadex的引用

Bre*_*ett 5 c mingw build ld

我正在使用MinGW.我有一些代码调用malloc和一些其他通用函数.当我输入:

gcc TestCode.c
Run Code Online (Sandbox Code Playgroud)

我得到一个a.exe文件,它工作得很完美,我没有得到任何警告.

如果我输入:

gcc -c TestCode.c -o TestCode.o
ld *.o
Run Code Online (Sandbox Code Playgroud)

我得到了一大堆警告,例如:

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'
Run Code Online (Sandbox Code Playgroud)

我假设这是我如何调用链接器的问题.因此,如果不清楚问题是什么,我只会发布代码.我希望这是一个简单的解决方案,我只是忘记在链接时包含一些超级明显的库.

Car*_*rum 7

ld似乎默认情况下不会链接任何库.从您的错误消息,您似乎至少需要C运行时和libc.使用gcc链接,以便为您链接在一些方便的默认值:

gcc -c TestCode.c -o TestCode.o
gcc *.o
Run Code Online (Sandbox Code Playgroud)

如果您真的ld直接使用,那么您需要找出C运行时库和libc的名称.例如(假设库命名为libcrtlibc):

ld *.o -lcrt -lc
Run Code Online (Sandbox Code Playgroud)