You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mac编译C程序遇ld链接错误:Undefined symbols: _main,寻求解决方案

解决Mac编译C程序时的_main未定义链接错误

问题重现

编译C程序时出现链接错误:

ld: Undefined symbols:
     _main, referenced from:
     <initial-undefines>

使用的C代码为标准Hello World程序:

#include <stdio.h>

int main() {
  printf("Hello, World!\n");
  return 0;
}

已重装Xcode及命令行工具,问题仍存在。

可行解决方案

  • 检查编译命令是否完整
    若仅执行编译步骤生成目标文件(比如用gcc -c hello.c),直接运行.o目标文件会触发该错误。正确的编译+链接命令是:

    gcc hello.c -o hello
    # 或直接使用clang
    clang hello.c -o hello
    

    执行完成后运行./hello即可。

  • 确认文件后缀为.c
    若文件后缀是.cpp或其他非.c格式,编译器会以C++模式处理代码,虽不会直接导致_main未定义,但建议确保后缀为.c,避免编译模式差异。

  • 手动指定标准库链接
    若编译器默认参数异常,可手动指定链接C标准库:

    gcc hello.c -o hello -lc
    
  • 修复命令行工具
    重新执行命令行工具安装/修复命令,之后重启终端再尝试编译:

    xcode-select --install
    

内容的提问来源于stack exchange,提问作者Flames

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 18:43:20