gpt4 book ai didi

c++ - Clion 链接失败

转载 作者:行者123 更新时间:2023-11-30 02:33:23 26 4
gpt4 key购买 nike

我有一个头文件

// 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})

我从 main.cpp 调用 graph_t *g = graph_create(15); 并收到以下错误,指出该方法未定义:

"C:\Program Files (x86)\JetBrains\CLion 1.2.4\bin\cmake\bin\cmake.exe" --build C:\Users\Shiro.CLion12\system\cmake\generated\6e6ca233\6e6ca233\Debug --target Thesis -- -j 8 Scanning dependencies of target Thesis [ 66%] Building CXX object CMakeFiles/Thesis.dir/main.cpp.obj [ 66%] Building C object CMakeFiles/Thesis.dir/graph.c.obj [100%] Linking CXX executable Thesis.exe CMakeFiles\Thesis.dir/objects.a(main.cpp.obj): In function main': C:/Users/Shiro/ClionProjects/Thesis/main.cpp:7:
undefined reference to
graph_create(int)' collect2.exe: error: ld returned 1 exit status CMakeFiles\Thesis.dir\build.make:121: recipe for target 'Thesis.exe' failed mingw32-make.exe[3]: [Thesis.exe] Error 1 CMakeFiles\Makefile2:66: recipe for target 'CMakeFiles/Thesis.dir/all' failed CMakeFiles\Makefile2:78: recipe for target 'CMakeFiles/Thesis.dir/rule' failed Makefile:117: recipe for target 'Thesis' failed mingw32-make.exe[2]: [CMakeFiles/Thesis.dir/all] Error 2 mingw32-make.exe[1]: [CMakeFiles/Thesis.dir/rule] Error 2 mingw32-make.exe: [Thesis] Error 2

我做错了什么?

最佳答案

假设函数定义在 graph.c C 源文件中,问题是因为 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
#endif

关于c++ - Clion 链接失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35555166/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com