【问题标题】:C compiling - 'undefined reference to function' when trying to link object filesC 编译 - 尝试链接目标文件时出现“未定义的函数引用”
【发布时间】:2017-09-20 09:25:45
【问题描述】:

所以我创建了目标文件

cc -c MAIN.C
cc -c tablero.c

但是当我尝试将它们链接到可执行文件时

cc MAIN.o tablero.o

我明白了

undefined reference to `asdf()'

(在 tablero.c 中定义并在 MAIN.C 中调用的函数)

这是我的文件:

我有 MAIN.C

#include <stdio.h>
#include <cstring>
#include "tablero.h"
int main()
{
   int c;
   printf( "Enter a value :");
   c = getchar( );
   putchar(c);
   printf( "\nYou entered: ");
   c = asdf ();
   putchar(c);
   return 0;
}

我有 tablero.h

#ifndef TABLERO_H_
#define TABLERO_H_
int asdf();
#endif // TABLERO_H_

我有 tablero.c

#include "tablero.h"
int asdf() {return 48;}; //48 is 0 in ascii

【问题讨论】:

  • 在我的系统上工作(ubuntu gnome 16.04,虽然我不得不删除 cstring)
  • 请注意,&lt;cstring&gt; 是 C++ 标头,而不是 C 标头。不过,不清楚您是否需要它——不管是什么语言。
  • @PriyeshKumar:你真的将文件命名为“MAIN.C”而不是“MAIN.c”吗?
  • 是的,我错过了。我用的是小c
  • +1 用于实际显示完整的最小示例和实际的文件名和命令,包括大小写和所有内容!

标签: c


【解决方案1】:

你已经被许多 Unixy 系统上的 cc 工具的一个不起眼的功能所困扰:后缀为小写 .c 的文件被编译为 C,但后缀为 大写 @987654323 的文件@ 编译为 C++!因此,您的 main(编译为 C++)包含对 mangled 函数名称的外部引用,asdf()(又名 _Z4asdfv),但 tablero.o(编译为 C)只定义了一个未修改名称,asdf

这也是为什么您能够将 C++ 头文件 &lt;cstring&gt; 包含在原本应成为 C 程序的内容中。

MAIN.C重命名为main.c(并将&lt;cstring&gt;改为&lt;string.h&gt;),重新编译main.o,你的程序就应该链接了。

如果您确实想要将程序的一部分编译为 C,一部分编译为 C++,那么您可以使用 extern "C" 注释您的头文件以使符号匹配:

#ifndef TABLERO_H_
#define TABLERO_H_

#ifdef __cplusplus
extern "C" {
#endif

int asdf(void);

#ifdef __cplusplus
}
#endif

#endif // TABLERO_H_

这样的头文件必须格外小心,以仅包含在 C 和 C++ 中具有相同含义的代码。只有 POD 类型,没有 C++ 关键字,也没有 C99-but-not-C++ 关键字,没有重载等等。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-21
    • 2016-12-10
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-15
    • 2015-06-25
    相关资源
    最近更新 更多