c - 如何诊断 Xcode 消息 “Linker command failed with exit code 1” ?

标签 c xcode

我正在尝试自学一些 C,但我几乎立刻就陷入了 xCode 的困境。目前我的文件夹结构如下所示:

enter image description here

main.c 看起来像这样:

#include <stdio.h>

int main(void)
{
    int dogs;

    printf("How many dogs do you have?\n");
    scanf("%d", &dogs);
    printf("So you have %d dog(s)! \n", dogs);

    return 0;
}

concrete.c 看起来像这样:

#include <stdio.h>
int main(void)
{
    printf("Concrete contains gravel and cement.\n");

    return 0;
}

无论我通过“产品”->“运行”运行哪一个,我都会遇到相同的错误:

enter image description here

有什么想法造成这种情况吗?仅来自 Python 背景,因此这些错误和 xCode 对我来说都是全新的

编辑-删除crete.c文件解决了这个问题,但这对我来说似乎不合理。是因为我有 2 个带有 int main(void) 的文件吗?

最佳答案

当您单击 Xcode 显示的“链接器命令失败,退出代码 1”时,它应该向您显示构建日志中链接器显示消息并以代码 1 退出的部分。

这些消息包括:

duplicate symbol _main in:
[Some path on your system…]/Build/Intermediates.noindex/foo.build/Debug/foo.build/Objects-normal/x86_64/foo.o
[Some path on your system…]/Build/Intermediates.noindex/foo.build/Debug/foo.build/Objects-normal/x86_64/main.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

该消息“duplicate symbol _main”告诉您问题:您有两个 main 定义。 main 是为启动程序而调用的唯一例程的名称,您应该只有一个定义。

补充

默认情况下,在 C 语言中,函数名称具有外部链接,这意味着不同翻译单元(正常使用时的源文件)中的相同名称引用相同的事物。因此,不能有两个函数具有相同的名称(任何名称,而不仅仅是 main),因为这样您就有了两个具有相同名称的东西。您可以通过使用静态声明来给函数提供内部链接而不是外部链接,这样该名称就不会与其他翻译单元中的相同名称发生冲突。

尽管如此,定义 mainstatic 版本可能会导致编译器提示,因为 main 不应该用 static 声明 并且应该声明它返回 int(如果您以其他方式声明它)。这些源自 C 标准中的文本,位于 C 2018 5.1.2.2.1 1:

The function called at program startup is named main. The implementation declares no prototype for this function. It shall be defined with a return type of int and with no parameters: … or with two parameters (referred to here as argc and argv, though any names may be used, as they are local to the function in which they are declared): …

尽管该文本限制了 main 的声明,但在我看来,它可以被解释为引用具有外部链接的 main,而不是发生的任何例程被声明为main。尽管如此,将众所周知的特殊用途名称重复用于其他目的通常是不好的做法。

关于c - 如何诊断 Xcode 消息 “Linker command failed with exit code 1” ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54848214/

相关文章:

Xcode 4 最有用的快捷键

c - 如何在不使用命令行的情况下在 GPU 上执行 ffmpeg 代码?

c - 动态字符串数组

objective-c - 剪辑 View 的框架在 Xcode 5 和 Objective-C 中的运行时错误会有所不同

objective-c - 在 NSString 搜索栏中不断搜索子字符串

xcode - 在CMake的后期制作步骤中将目标文件复制到另一个位置

ios - 停止 Swift 中小数分隔符的重复

c - 段错误(核心转储)[康威的生命游戏]

c - 如何将 CHAR 数组存储为字符串 MAC 地址

c - 为什么 ID2D1Factory::GetDesktopDpi 已过时?