How to use import library from build dir in cmake?

371 views Asked by At

For example I have 2 independent(! and they should be independent!) build tasks.

First task build the library.

Second task build binary that should use libary from the first task. I dont need any type of install library, instead I just need to use library in build tree that was build by first task.

So in the cmake script of the library I add followed string:

...
export(TARGETS ${PROJECT_NAME} FILE MyLibConfig.cmake)
...

Then I think in binary cmake script I should do somehow import and additionally pass the path to the librarys MyLibConfig.cmake as a command line parameter

There are a lot if info about export, but no one info how to do import.

Could smbody explain?

PS: but please explain by own words, don`t give just a link - I read a lot of them and all it is unclear and does not works :(

UPD3: Ok, lets try to make some simple example.

The library consist of 3 files

// MyLib.h
#pragma once

int MyFunc();

//------------------------------------
// MyLib.cpp
#include "MyLib.h"

int MyFunc()
{
    return 5;
}

And the cmake-file

cmake_minimum_required (VERSION 3.17)
project (MyLib)

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")   # binaries
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib")   # static lib
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")   # shared lib

add_library(${PROJECT_NAME} MyLib.cpp)

target_include_directories(${PROJECT_NAME}
    PUBLIC
        $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/..>
)

export(TARGETS ${PROJECT_NAME} FILE MyLibConfig.cmake)

The binary project consist of 2 files

cmake_minimum_required (VERSION 3.17)
project (MyBin)

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")   # binaries
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/lib")   # static lib
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin")   # shared lib

add_executable(${PROJECT_NAME} Main.cpp)

set(CMAKE_INCLUDE_CURRENT_DIR ON)

find_package(MyLib REQUIRED)
target_link_libraries(${PROJECT_NAME} PUBLIC MyLib)

And the .cpp-file

//Main.cpp
#include <iostream>
#include <MyLib.h>

int main()
{
    int k = MyFunc();
    ++k;
    
    return 0;
}

I launch cmake for binary build with MyLib_DIR variable path to generated MyLibConfig.cmake

CMake finished work without any errors, but I receive compilation error

Main.cpp(2): fatal error C1083: Cannot open include file: 'MyLib.h': No such file or directory

What and how I should to fix?

0

There are 0 answers