How can i link a custom library with Cmake?

57 Views Asked by At

im new in Cmake, im trying to link a library to a project using Cmake, the following code is this:

code of the header:

my_library.h

    #ifndef MY_LIBRARY
    #define MY_LIBRARY

    int get_random_number();

    #endif

implementation of the header: my_library.cpp

    #include "my_library.h"

    int get_random_number(){

            return 46;
    }

Configuration of Cmake

CmakeLists.txt

    cmake_minimum_required(VERSION 3.8)

    file(GLOB_RECURSE SOURCES LIST_DIRECTORIES true *.h *.cpp)

    set(SOURCES ${SOURCES})

    add_library(my_library SHARED ${SOURCES})

    target_include_directories(my_library PUBLIC ${CMAKE_CURRENT_LIST_DIR})

outside the folder i have this:

main.cpp

#include <iostream>
#include "my_library.h"
    int main(){

            std::cout<<"Hello, jairo"<<std::endl;
            std::cout<<"A random number is: "<<get_random_number()<<std::endl;

            return 0;

    }

CmakeListst.txt

    cmake_minimum_required(VERSION 3.20)

    project(Hello CXX)

    add_subdirectory(my_library)

    add_executable(${PROJECT_NAME} main.cpp)

    target_link_libraries(${PROJECT_NAME} PUBLIC my_library)

the structure of the whole project is this:

all goes well until y try to execute the Hello.exe file that is generated, windows gives an error saying "Code execution cannot continue because libmy_library.dll was not found" which i undestand as CMake is not linking correctly the library

the structure of the project is this

  • main.cpp
  • CmakeLists.txt
  • -my_library(folder)
  • ---my_library.h(inside the folder)
  • ---my_library.cpp(inside the folder)
  • ---CmakeLists.txt(inside the folder)

im using mingw as compiler and executing all comands with cmd of windows

i have tryed everything, uninstall and install again cmake, adding the target_include_directories but it doesnt work

0

There are 0 best solutions below