use*_*515 1 c++ linker cmake calling-convention extern
我正在尝试构建一个从 C++ 调用 C 代码的 CMake 项目,尽管我(据我所知)正确使用了“extern C”,但我得到了未定义的符号。
CMakeLists.txt:
cmake_minimum_required(VERSION 3.0)
project(CTest LANGUAGES CXX)
add_executable(test main.cpp lib.c)
Run Code Online (Sandbox Code Playgroud)
主要.cpp:
#include "lib.h"
int main()
{
printit();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
库.c:
#include <stdio.h>
#include "lib.h"
int printit()
{
printf("Hello world\n");
return 0;
}
Run Code Online (Sandbox Code Playgroud)
库.h:
extern "C" int printit();
Run Code Online (Sandbox Code Playgroud)
这给了我一个“未定义的 printit 引用”错误。
如果我只是从命令行构建它,它就可以正常工作:
g++ main.cpp lib.c
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
extern "C"
是C++语法。因此,您的头文件 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 */
Run Code Online (Sandbox Code Playgroud)
由于您同时拥有 C 和 CXX 源,您的项目调用也应该project(CTest LANGUAGES C CXX)
在 CMakeLists.txt 中启用 C。
归档时间: |
|
查看次数: |
2373 次 |
最近记录: |