Home > Blockchain >  How to add a library to a project so that if the library changes, it (the lib) gets recompiled first
How to add a library to a project so that if the library changes, it (the lib) gets recompiled first

Time:08-18

I'm developing a simple library and in the past I've been using Premake. Now, I want to change that and use CMake. I've been struggling with 'porting' my workflow to CMake.

I want to have 2 projects, one for the library and one for the testing program. The library should not be dependent on the testing program but the testing program should include the library and be dependent on it. For example, if I change something in the library and compile my testing program, I want the library to recompile and then the testing program, so that it uses the latest library version.

I was able to do that in Premake but I just can't seem to figure it out yet in CMake. From my understanding, there should a top level CMake file and then the library should have one and the program should have one, just like I did in Premake.

Currently I only managed to create my library CMake file, but nothing else. A little help would be appreciated, especially as I'm noob in CMake.

My project structure looks like this

Root
├───Application
│   ├───Assets/
│   └───src/
│       └───Scenes/
├───Library
    ├───BUILD/
    ├───include/
    └───src/
    └───CMakeLists.txt

CodePudding user response:

Have just one project with a single CMakeLists.txt in the root, something like this

cmake_minimum_required( VERSION 3.0 )
project( MainProject )
add_subdirectory( Library )
add_subdirectory( Application )

Once you add the Library as a dependency of Application it all should work. Example:

# in Library/CMakeLists.txt
add_library( mylib SHARED file1.cpp file2.cpp )

Then in the app

# in Application/CMakeLists.txt
add_executable( myapp main.cpp )
target_link_libraries( myapp mylib )

that should recompile both mylib and relink myapp as soon as either file1.cpp or file2.cpp change.

UPDATE (to address comments)

I typically set up both debug and release folders with a shell script prior, something like this:

#!/usr/bin/bash
# put this on the root together with your CMakelists.txt
SCRIPT_NAME=${BASH_SOURCE:-$0}
SCRIPT_DIR=$(readlink -f $(dirname "$SCRIPT_NAME") )
BUILD_DIR=${SCRIPT_DIR}/build

for build_type in release debug relwithdebinfo; do
    
    echo ">>>>> Build Type:" $build_type "<<<<<<"
    rm -rf ${BUILD_DIR}/${build_type}
    mkdir -p ${BUILD_DIR}/${build_type}
    cd ${BUILD_DIR}/${build_type}

    cmake -G Ninja \
        -DCMAKE_BUILD_TYPE=$build_type \
        ${SCRIPT_DIR} 
done

Then you just switch to cd build/debug and run ninja (or make). When you are done debugging, switch to release folder cd ../release and build it again/install.

  • Related