c++cmakekdevelop

How to use / include libraries in Cmake / Kdevelop


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.


Solution

  • /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.