Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add external c++ libraries to a CLion project

I am using CLion from Mac, and i'm having problems to understand how can i add external libraries to my project. So, how can i add external libraries to a c++ project?

like image 379
PazzoTotale Avatar asked Jul 09 '17 15:07

PazzoTotale


People also ask

How do I add an external library to CLion?

Since CLion relies on CMake build system, you can do this with CMake commands. To add libraries to your project, use find_package (if you use separate libraries, for example, installed in the system) and target_link_libraries CMake commands.

How do I add an external C++ library to my project?

Go to the Project menu. Go to Build Options... In the options dialog, select the Linker Settings tab. Use the Add button to select a library and add it to your project.

How do I open a new C file in CLion?

Create a new C/C++ source file In the Project tool window, select the directory in which you want to add new files. Right-click it and select New | C/C++ Source File from the context menu. In the dialog that opens: Specify the name of a file.


2 Answers

Manually edit CMakeLists.txt adding the following lines at the end with the proper paths for your system and proper ProjectName. This config is for an Ubuntu 17.04 workstation.

include_directories("/usr/include/SDL2")
target_link_libraries(ProjectName "/usr/lib/x86_64-linux-gnu/libSDL.so")

Hope this helps.

You can test it with the following:

#include <iostream>
#include <SDL.h>
using namespace std;

int main() {
    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        cout << "SDL Init failed" << endl;
        return 1;
    }
    cout << "SDL Init succeeded" << endl;

    SDL_Quit();
    return 0;
}
like image 137
Kevin Genus Avatar answered Sep 16 '22 20:09

Kevin Genus


in CMakeLists.txt, add external library information. first, you can define a logical name for the external library, say for e.g. we want to link a shared library which has .so file somewhere already installed on the system,

add_library(myLogicalExtLib SHARED IMPORTED)

IMPORTED means that the library already exists and we don't need to build it here in this project.

then, we can supply the location information about this logical library as follows,

set_target_properties(myLogicalExtLib PROPERTIES IMPORTED_LOCATION "/usr/lib/x86_64-linux-gnu/my_logical_ext_lib.so")

like image 23
ameet chaubal Avatar answered Sep 17 '22 20:09

ameet chaubal