How to create a cmake interface library(header only library) and link it in another project
Interface library printer
contains three files CMakeLists.txt, print.hpp and print.inl
CMakeLists.txt
cmake_minimum_required(VERSION 3.0.0)
project(printer VERSION 0.1.0)
include(CTest)
enable_testing()
add_library(printer INTERFACE print.hpp print.inl)
set_target_properties(printer PROPERTIES CXX_STANDARD 20)
set_target_properties(printer PROPERTIES LINKER_LANGUAGE CXX)
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)
print.hpp
#ifndef PRINT_H
#define PRINT_H
template<typename T>
void print(const T& t);
#include "print.inl"
#endif
print.inl
#include <iostream>
template<typename T>
void print(const T& t) {
std::cout << t << std::endl;
}
Print_App
project includes the above interface library
CMakeLists.txt
cmake_minimum_required(VERSION 3.0.0)
project(print_app VERSION 0.1.0 LANGUAGES CXX)
include(CTest)
enable_testing()
add_executable(print_app
main.cpp
)
set_target_properties(print_app PROPERTIES CXX_STANDARD 20)
target_link_libraries(print_app INTERFACE printer)
set(CPACK_PROJECT_NAME ${PROJECT_NAME})
set(CPACK_PROJECT_VERSION ${PROJECT_VERSION})
include(CPack)
main.cpp
#include <iostream>
// how to include the below header file without specifying the relative path like below
// #include "print.hpp"
#include "../stlib/print.hpp"
int main() {
std::cout << "Hello, world!" << std::endl;
print(10);
print("abc");
print(1.23456789);
}
In the Makefile of print_app
, I see no mention of printer
library.