我正在尝试构建一个从 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/