1

I want to use cJSON library on windows with clion. I have copied cJSON.h and cJSON.c to my project directory. I have included cJSON.h with this command: #include "cJSON.h" When I try to compile my project, I get these errors:

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

3 Answers3

0

Seems like you did not add the cjson.c file to your build and this cause the link errors you get, or you may add c files (cjson.c) to c++ project, and you are missing 'extern C' prefix at your cjson.h header.

Eliyahu Machluf
  • 1,251
  • 8
  • 17
0

Check your CMakeLists.txt file, under set(SOURCE_FILES) you should add the cJson files if not already present together with your own. Something like:

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

If that doesn't work or if they are already present you can try writing extern C {...} with the whole cJson.h content between the parenthesis if you are trying to use a C library with C++

John Doe
  • 1,613
  • 1
  • 17
  • 35
  • Since I'm using c and all the files are in the same directory, I changed your set command and I get the same errors: set(SOURCE_FILES main.c cJSON.c cJSON.h) – Pouya Esmaili Dec 19 '19 at 15:25
0

I just solved the problem. The only thing I needed to do was to add cJSON.h and cJSON.c to the add_executable function of CMakeLists.txt like this:

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