5

I don't understand what I need to do to use a library which is located in /usr/include.

For example: I want to use the json library which is located in /usr/include/json. In my project 'main.cpp' I do #include <json/json.h>.

I don't get any errros but when I start to use the functions in the library I get undefined reference errors. I have this problem with multiple libraries, I have no idea what to do I searched on google but I only came across vague answers.

I'm pretty sure I need to do something in the CMakeLists.txt file but I have no idea what.

Zero
  • 355
  • 1
  • 4
  • 12
  • There are two parts to using a library in C++; the headers (telling your program what symbols are available) and the binaries (that provide those symbols). You've got the headers (so your program knows the symbols exist somewhere) but not the libraries (so it doesn't have a definition for those symbols, hence your error). You need to link in the appropriate library to resolve the errors. – OMGtechy Mar 31 '16 at 09:36
  • Everything is written in json library readme. Just read it carefully. – zoska Mar 31 '16 at 12:53

1 Answers1

6

/usr/include is accessible for include by default. But when you include an external library, you must link it to your target. In case you are using cmake this can be done as follows: add to your CMakeLists.txt the following line:

target_link_libraries(your_target_name your_library_name)

For example, on my machine (Fedora 21) jsoncpp package is named jsoncpp, and it's include files are in /usr/include/jsoncpp/json. So I create test.cpp like this

#include <jsoncpp/json/json.h>
#include <iostream>

int main(int, char**)
{
    Json::Value val(42);
    Json::StyledStreamWriter sw;
    sw.write(std::cout, val);   
    return 0;
}

and CMakeLists.txt

add_executable(test
test.cpp
)

target_link_libraries(test jsoncpp)

and all works well.

Caleb Koch
  • 656
  • 1
  • 9
  • 15
user2807083
  • 2,962
  • 4
  • 29
  • 37
  • I did what you said and now it says: `cannot find -ljsoncpp` My path is: `usr/include/jsoncpp/json`. My `CmakeLists.txt`: `add_executable(cpptest main.cpp)` `target_link_libraries(cpptest jsoncpp)` `install(TARGETS cpptest RUNTIME DESTINATION bin)` – Zero Mar 31 '16 at 10:14
  • What system you use? – user2807083 Mar 31 '16 at 10:15
  • Linux Debian 8 32 bit – Zero Mar 31 '16 at 10:18
  • 1
    Is `libjsoncpp` package installed and how it is named exactly? – user2807083 Mar 31 '16 at 10:19
  • 2
    My bad, I copied the files from the github include to usr/include. Now I downloaded the correct package `libjsoncpp-dev` and it is working now! Thanks! – Zero Mar 31 '16 at 10:25
  • I seem to recall KDevelop had a configuration panel for the linker. Why did I need to edit CMakeList.txt manually in 2018? – Phlip Oct 05 '18 at 19:59