Skip to content

Instantly share code, notes, and snippets.

@cristianadam
Created February 9, 2025 18:38
Show Gist options
  • Save cristianadam/ac36a6bfe1b03b604defd45bad10959f to your computer and use it in GitHub Desktop.
Save cristianadam/ac36a6bfe1b03b604defd45bad10959f to your computer and use it in GitHub Desktop.
CMake using add_custom_target and add_dependencies
cmake_minimum_required(VERSION 3.20)
project(deps)
file(WRITE ${CMAKE_BINARY_DIR}/library.cpp "
#include <fstream>
#include <string>
std::string message()
{
std::ifstream is(\"message.txt\");
return std::string(std::istreambuf_iterator<char>(is), std::istreambuf_iterator<char>());
}
")
file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
file(WRITE ${CMAKE_BINARY_DIR}/lib/message.txt "Hello Library World!")
file(WRITE ${CMAKE_BINARY_DIR}/main.cpp "
#include <iostream>
#include <string>
std::string message();
int main()
{
std::cout << message() << std::endl;
return 0;
}
")
add_library(msg ${CMAKE_BINARY_DIR}/library.cpp)
add_custom_target(msg_dep COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/lib/message.txt ${CMAKE_BINARY_DIR}/message.txt)
add_dependencies(msg msg_dep)
add_executable(exe ${CMAKE_BINARY_DIR}/main.cpp)
target_link_libraries(exe PRIVATE msg)
add_custom_target(run COMMAND exe)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment