0

这是我的2个源文件:

主.c:

#include <stdio.h>
#include "part2.c"

extern int var1;
extern int array1[];

int main()
{
    var1 = 4;
    array1[0] = 2;
    array1[1] = 4;
    array1[2] = 5;
    array1[3] = 7;

    display();

    printf("---------------");

    printf("Var1: %d", var1);
    printf("array elements:");

    int x;
    for(x = 0;x < 4;++x)
        printf("%d: %d", x, array1[x]);

    return 0;
}

第 2 部分.c

#include <stdio.h>

int var1;
int array1[4];

void display(void);

void display(void)
{
    printf("Var1: %d", var1);
    printf("array elements:");

    int x;
    for(x = 0;x < 4;++x)
        printf("%d: %d", x, array1[x]);
}

当我尝试编译程序时,这就是我得到的:

ld /Users/John/Library/Developer/Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Products/Debug/Test normal x86_64 cd /Users/John/Xcode/Test setenv MACOSX_DEPLOYMENT_TARGET 10.7 /Applications/Xcode.app/Contents/Developer/工具链/XcodeDefault.xctoolchain/usr/bin/clang -arch x86_64 -isysroot /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.7.sdk -L/Users/John/Library /Developer/Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Products/Debug -F/Users/John/Library/Developer/Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Products/Debug -filelist /Users/John/Library/Developer /Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Intermediates/Test.build/Debug/Test.build/Objects-normal/x86_64/Test.LinkFileList -mmacosx-version-min=10。7 -o /Users/John/Library/Developer/Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Products/Debug/Test

ld:在 /Users/John/Library/Developer/Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Intermediates/Test.build/Debug/Test.build/Objects-normal/x86_64/part2.o 和 /Users/ 中重复符号_display John/Library/Developer/Xcode/DerivedData/Test-blxrdmnozbbrbwhcekmouessaprf/Build/Intermediates/Test.build/Debug/Test.build/Objects-normal/x86_64/main.o for architecture x86_64 clang:错误:链接器命令失败,退出代码1(使用 -v 查看调用)

我正在使用 Xcode,这两个文件都在一个名为的 C 项目中Test

是什么导致了错误,我该如何解决?

4

1 回答 1

5

去掉“ #include "part2.c"”,改成“ #include "part2.h

并移动您的函数声明:

void display(void);

从“ part.c”文件的顶部到名为“ part2.h”的文件中,该文件应包含在两个 .c 文件中(或放在其顶部)。

于 2012-06-28T21:13:33.977 回答