在 windows 中使用 cJSON

Using cJSON in windows

我想在 windows 上与 clion 一起使用 cJSON 库。我已将 cJSON.h 和 cJSON.c 复制到我的项目目录中。我在这个命令中包含了 cJSON.h:#include "cJSON.h" 当我尝试编译我的项目时,出现以下错误:

CMakeFiles\Client.dir/objects.a(main.c.obj): In function `parse':
.../main.c:117: undefined reference to `cJSON_Parse@4'
.../main.c:121: undefined reference to `cJSON_GetErrorPtr@0'
.../main.c:127: undefined reference to `cJSON_GetObjectItemCaseSensitive@8'
.../main.c:128: undefined reference to `cJSON_GetObjectItemCaseSensitive@8'
.../main.c:131: undefined reference to `cJSON_IsString@4'
.../main.c:131: undefined reference to `cJSON_IsString@4'
.../main.c:141: undefined reference to `cJSON_Delete@4'
collect2.exe: error: ld returned 1 exit status
CMakeFiles\Client.dir\build.make:84: recipe for target 'Client.exe' failed
mingw32-make.exe[3]: *** [Client.exe] Error 1
mingw32-make.exe[2]: *** [CMakeFiles/Client.dir/all] Error 2
mingw32-make.exe[1]: *** [CMakeFiles/Client.dir/rule] Error 2
CMakeFiles\Makefile2:71: recipe for target 'CMakeFiles/Client.dir/all' failed
CMakeFiles\Makefile2:83: recipe for target 'CMakeFiles/Client.dir/rule' failed
Makefile:117: recipe for target 'Client' failed
mingw32-make.exe: *** [Client] Error 2

似乎您没有将 cjson.c 文件添加到您的构建中,这会导致您收到 link 错误,或者您可以将 c 文件 (cjson.c) 添加到 C++ 项目,并且您在 cjson.h header.

处缺少 'extern C' 前缀

检查您的 CMakeLists.txt 文件,在 set(SOURCE_FILES) 下您应该添加 cJson 文件(如果您自己的文件不存在)。类似于:

set(SOURCE_FILES src/main.cpp include/main.h src/cJson.c include/cJson.h)

如果这不起作用或者它们已经存在,如果您尝试将 C 库与 C++ 一起使用,您可以尝试在括号之间使用整个 cJson.h 内容编写 extern C {...}

我刚刚解决了这个问题。我唯一需要做的就是将 cJSON.h 和 cJSON.c 添加到 CMakeLists.txt 的 add_executable 函数中,如下所示:

add_executable(ProjectName main.c cJSON.h cJSON.c)