简体   繁体   中英

c++ Generating static library and then using it with Clion/Cmake

I've been searching the web and trying for a few hours to get this to work. However I'm running into a brick wall.

I have a small collection of helper classes that can be very useful across projects. I want to put these into a static library so I can include it on any project I work on.

I have successfully created a file libMyTestLibrary.a and put it in my /usr/lib/ folder. The problem I am running into now is using that static library in a different Clion project (version 1.2 running on linux Mint 17.2)

I will be using some very simple stand in classes to demonstrate the process.

The myTestClass.h file:

//assume header guard, etc. 
class myTestClass
{
public:
    int add(const int& lhs, const int& rhs) const;
};

The myTestClass.cpp file:

#include "myTestClass.h"

int myTestClass::add(const int &lhs, const int &rhs) const
{
    return lhs + rhs;
}

To generate the .a file I am following the instructions in this tutorial .

I run the following terminal commands:

beaky@BeakyDesktop ~/Documents/Programming/testProject $ g++ -c myTestClass.cpp

This successfully generates a myTestClass.o file. Then I run:

beaky@BeakyDesktop ~/Documents/Programming/testProject $ ar cr libMyTestLibrary.a myTestClass.o

My .a file has been created. I then move it into /usr/lib/ using the command:

beaky@BeakyDesktop ~/Documents/Programming/testProject $ sudo mv libMyTestLibrary.a /usr/lib/

The .a library now lives in my /usr/lib folder.

I create a new Clion project called testProject2 where I want to use my newly created library. Here is where I am running into trouble!

In my CMakeLists.txt file I include the line:

TARGET_LINK_LIBRARIES(testProject2 /usr/lib/libMyTestLibrary.a)

I though this would fully include the library in my project that way in main.cpp (or anywhere else) and that I could do something like:

#include "myTestClass.h"

int main()
{
    int result = add(1, 3);
    return 0;
}

However this results in errors! myTestClass.h could not be found. Am I including this static library correctly? Am I right to assume that I should be using Cmake to include my custom library? If so what is the correct way to include my custom .a file my project using clion and cmake?

The CMake command target_link_libraries only tell CMake to link with the specific library, it will not do anything else.

You need to specify where there header files are so the preprocessor can find them. This is done with the include_directories command.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM