代码之家  ›  专栏  ›  技术社区  ›  Pillo

C-在Mac OSX Lion上编译时用于体系结构x86_64的未定义符号

  •  13
  • Pillo  · 技术社区  · 13 年前

    我在Mac OSX Lion上编译一个非常简单的name.c文件时遇到了一些问题。

    现在,我开始在CS50.net上学习哈佛CS50课程。我对编程并不完全陌生,但我很好奇这门课程是如何教授的。

    这是名称的来源。c:

    #include <stdio.h>
    #include <cs50.h>
    
    int
    main(void)
    {
        printf("State your name:\n");
        string name = GetString();
        printf("O hai, %s!\n", name);
        return 0;
    }
    

    正如您所看到的,它需要这个库: https://manual.cs50.net/CS50_Library

    现在,当我编译它时,会发生以下情况:

    Undefined symbols for architecture x86_64:
      "_GetString", referenced from:
          _main in name-vAxcar.o
    ld: symbol(s) not found for architecture x86_64
    clang: error: linker command failed with exit code 1 (use -v to see invocation)
    make: *** [name] Error 1
    

    如果我在源文件中使用相同的GetString()cs50.c函数,那么它可以完美地工作:

    #include <stdio.h>
    #include <string.h>
    #include <float.h>
    #include <limits.h>
    #include <stdbool.h>
    #include <stdlib.h>
    
    typedef char *string;
    
    string GetString(void);
    
    int
    main(void)
    {
        printf("State your name:\n");
        string name = GetString();
        printf("O hai, %s!\n", name);
     }
    
    string
    GetString(void)
    {
        // CODE
    }
    

    为什么会发生这种情况? 我按照上面链接上的说明安装了图书馆;我检查了cs50.h和libcs50.a分别位于/usr/local/include和/usr/local/lib中。

    提前感谢您的帮助。

    1 回复  |  直到 9 年前
        1
  •  19
  •   user1071136    13 年前

    您遇到的问题是在链接阶段,而不是编译阶段。您没有提供 GetString ,仅其声明(通过 .h 向您提交文件 #include )。

    为了提供实现本身,您通常需要链接到包含它的库;这通常是由 -l 标记到 g++ 例如

    g++ file.cpp -lcs50
    

    您的第二个示例代码确实链接了,因为您手动(并且显式)提供了 获取字符串 ,虽然是空的。