【问题标题】:MinGW undefined reference to malloc, free, sprintf, _beginthreadexMinGW 未定义对 malloc、free、sprintf、_beginthreadex 的引用
【发布时间】:2012-03-30 12:33:35
【问题描述】:

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

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'

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

【问题讨论】:

标签: c build mingw ld


【解决方案1】:

默认情况下,您的ld 似乎没有链接任何库。从您的错误消息看来,您至少需要 C 运行时和 libc。使用gcc 链接以获得一些方便的默认链接:

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

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

ld *.o -lcrt -lc

【讨论】:

  • 感谢您的指导!通过在我的 ld 上包含 -lmsvcrt 标志,我能够让它工作。不幸的是,项目构建可能太大,我们无法直接使用 ld,但感谢您的建议!
  • 使用 gcc 作为链接器的前端应该没有任何区别。您是什么意思“太大而无法使用 ld”?
【解决方案2】:

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

您可能应该这样做,因为在 CRT 和 Windows 支持库中的链接有相当多的细节(除非您非常具体地需要不使用默认运行时)。我当前的 MinGW 设置链接在以下项目中以及我的目标文件中:

crt2.o
crtbegin.o

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

crtend.o

使用--verbose 选项查看gcc 如何为您链接。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-06
    相关资源
    最近更新 更多