c++ - 在 CMake 项目中从 C++ 调用 C 代码。 undefined symbol 。有外部C

标签 c++ cmake linker extern calling-convention

我正在尝试构建一个从 C++ 调用 C 代码的 CMake 项目,但我得到了 undefined symbol ,即使我(据我所知)正确地使用了“extern C”。

CMakeLists.txt:

cmake_minimum_required(VERSION 3.0)
project(CTest LANGUAGES CXX)
add_executable(test main.cpp lib.c)

主要.cpp:

#include "lib.h"

int main()
{
    printit();
    return 0;
}

lib.c:

#include <stdio.h>
#include "lib.h"

int printit()
{
    printf("Hello world\n");
    return 0;
}

库.h:

extern "C" int printit();

这给了我一个“对 printit 的 undefined reference ”错误。

如果我只是从命令行构建它,它工作正常:

g++ main.cpp lib.c

我做错了什么?

最佳答案

extern "C" 是 C++ 语法。因此,您的 header lib.h 不能在 C 中使用。如果您按如下方式更改它,它也可以在 C++ 和 C 中使用。

#ifndef LIB_H_HEADER
#define LIB_H_HEADER

#ifdef __cplusplus
extern "C" 
{
#endif

int printit();

#ifdef __cplusplus
}
#endif

#endif /* LIB_H_HEADER */

因为您同时拥有 C 和 CXX 源,所以您的项目调用应该在您的 CMakeLists.txt 中启用 C 以及 project(CTest LANGUAGES C CXX)

关于c++ - 在 CMake 项目中从 C++ 调用 C 代码。 undefined symbol 。有外部C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54280003/

相关文章:

c++ - 视频文件读写

macos - MacOS 10.13.3 的 CMake 编译器标识未知

c - GCC 下与 Cortex-M0 的变量对齐

c++ - 我的矩阵类在初始化时崩溃

c++ - 为什么派生类的异常可以被基类的catch子句捕获?

cmake 检查库是否是静态的

c++ - CMake 编译失败

c++ - g++ 在构建点云库时未定义对符号 '__cxa_free_exception@@CXXABI_1.3' 的引用

c++ - 与ld合并节

c++ - OpenGL DevIL c++ 源代码