【发布时间】:2021-07-15 11:47:26
【问题描述】:
我正在尝试使用 extern "C" 在 Cpp 代码中访问我的两个 C 函数。我使用它如下:
#include <stdio.h>
#include <stdlib.h>
#include <cstdio>
extern "C"
{
#include "pltfrm.h"
#include "xil_printf.h"
}
int main()
{
init_platform();
print("Hello World\n\r");
print("Successfully ran Hello World application");
cleanup_platform();
return 0;
}
函数"init_platform" 和"cleanup_platform" 在"pltfrm.h" 中声明
我在这两个函数上都收到“未定义的引用”错误。我做错了什么? iam 使用 c++ 空项目模板的 eclipse 构建项目选项进行编译。
【问题讨论】:
-
这里的关键字是declared,而不是defined。您很可能没有链接它们。除非你确切地展示你是如何编译代码的,否则我们不能说太多。
-
模块中的函数是否编译为
c?要么您不链接它们,要么它们被编译为名称混乱的cpp函数,这也会导致undefined reference链接器错误,因为名称不匹配。 -
C++ 原生支持 C 代码。在您的情况下,
extern "C"是多余的,仅当 C 代码访问 C++ 函数时才需要它,反之亦然。 -
在两种语言中使用标头的常规方法是在标头中添加条件
extern "C"包装器。