2012-03-14 147 views
5

我正在使用MinGW。我有一些调用malloc和一些其他通用函数的代码。当我输入:MinGW未定义的引用malloc,free,sprintf,_beginthreadex

gcc TestCode.c 

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

如果我输入:

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

我收到了一大堆警告,如:

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' 

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

+1

可能重复[使用MinGW编译器时发生链接错误(无法找到__main)](http://stackoverflow.com/questions/4981826/link-error-while-using-mingw-compiler-cant-find-主) – 2012-03-14 03:25:29

回答

7

看起来您的ld默认情况下不链接任何库。从你的错误信息看来,你至少需要C运行时和libc。使用gcc链接以获得链接在一些方便的默认设置为您:

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

如果你真的使用ld直接,你将需要弄清楚你的C运行时库和libc中的名字。例如(假设库名为libcrtlibc):

ld *.o -lcrt -lc 
+1

感谢您的指导!我能够通过在我的ld中包含-lmsvcrt标志来使其工作。不幸的是,项目构建可能太大,我们不能直接使用ld,但感谢您的建议! – Brett 2012-03-14 03:31:12

+0

使用gcc作为链接器的前端应该没有任何区别。你的意思是“太大了,不愿意使用'ld'”? – 2012-03-14 03:55:42

1

由于Carl Norum said,您可以目标文件传递给gcc,它会知道它不需要编译它们 - 它只是将它们传递给链接器(不管你是否在同一个调用中编译其他源文件)。

而你应该这样做,因为在CRT和Windows支持库中有相当多的细节进入链接(除非你有一个非常特殊的需要不使用默认运行时)。在我的对象文件一起以下项目我目前的MinGW的设置链接:

crt2.o 
crtbegin.o 

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

crtend.o 

使用--verbose选项,看看你gcc链接。