我有一个头文件
// Creates a new graph with n vertices and no edges
graph_t *graph_create(int n);.c文件
graph_t *graph_create(int n)
{
graph_t *g;
int i;
//g = malloc(sizeof(graph_t));
g->V = n;
g->E = 0;
return g;
}这就是我的CMakeLists.txt的样子
cmake_minimum_required(VERSION 3.3)
project(Thesis)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp graph.h graph.c shared.h)
add_executable(Thesis ${SOURCE_FILES})我从graph_t *g = graph_create(15);调用main.cpp,并得到以下错误,说明该方法未定义:
"C:\Program (x86)\JetBrains\CLion 1.2.4\bin\cmake\bin\cmake.exe“--build 1.2.4\bin\cmake\bin\cmake.exe --目标论文-j 8扫描依赖关系,目标论文66%构建CXX对象CMakeFiles/Thesis.dir/main.cpp.obj 66%构建C对象CMakeFiles/Thesis.dir/graph.c.obj 100%链接CXX可执行文件Thesis.exe CMakeFiles\Thesis.dir/objects。a(main.cpp.obj):在函数
main': C:/Users/Shiro/ClionProjects/Thesis/main.cpp:7: undefined reference tograph_create(int)‘main': C:/Users/Shiro/ClionProjects/Thesis/main.cpp:7: undefined reference tograph_create(Int)中:错误: ld返回了1个退出状态CMakeFiles\Thesis.dir\build.make:121:目标' Thesis.exe’失败的配方32-make.exe 3:Thesis.exe错误1 CMakeFiles\Makefile2:66:目标‘CMakeFiles/Thesis.dir/所有’失败的CMakeFiles\Makefile2:78:目标的配方‘CMakeFiles/Thesis.dir/规则’failed :117:食谱为目标‘论文’失败Mingw32-make.exe 2: CMakeFiles/Thesis.dir/all Error 2 mingw32-make.exe 1: CMakeFiles/Thesis.dir/rule Error 2 mingw32-make.exe:论文错误2
我做错什么了?
发布于 2016-02-22 13:45:33
假设函数是在graph.c C源文件中定义的,问题在于https://en.wikipedia.org/wiki/Name_mangling。
C++使用损坏的名称来处理诸如重载之类的事情,C不需要这样做。当您想使用C源文件或C库中的函数时,需要告诉C++编译器不要使用损坏的名称,这是通过extern "C"构造完成的,如
extern "C" graph_t *graph_create(int n);但是,这有一个问题,那就是C编译器将不知道extern "C"是什么意思,它会抱怨。为此,您需要使用预处理器进行条件编译,并检查头文件是否由C++或C编译器使用。这是通过检查是否存在__cplusplus宏来完成的:
#ifdef __cplusplus
extern "C"
#endif
graph_t *graph_create(int n);如果您有多个函数,那么将它们放在一个支撑圈块中:
#ifdef __cplusplus
extern "C" {
#endif
graph_t *graph_create(int n);
// More functions here...
#ifdef __cplusplus
} // End of extern "C" block
#endifhttps://stackoverflow.com/questions/35555166
复制相似问题