1

Please see below minimal example:

CMakeLists.txt

cmake_minimum_required(VERSION 3.20)

project(sample)

add_executable(create_test1_test2 create_test1_test2.cpp)

add_custom_command(
  OUTPUT ${CMAKE_BINARY_DIR}/test1.txt ${CMAKE_BINARY_DIR}/test2.txt
  COMMAND ${CMAKE_BINARY_DIR}/create_test1_test2
  DEPENDS ${CMAKE_BINARY_DIR}/create_test1_test2)

add_executable(main main.cpp ${CMAKE_BINARY_DIR}/test1.txt)

add_custom_target(create_test2 DEPENDS ${CMAKE_BINARY_DIR}/test2.txt)

add_custom_command(
  OUTPUT ${CMAKE_BINARY_DIR}/test2.txt
  COMMAND ${CMAKE_COMMAND} -E copy ${CMAKE_BINARY_DIR}/test1.txt
          ${CMAKE_BINARY_DIR}/test2.txt
  DEPENDS ${CMAKE_BINARY_DIR}/test1.txt)

add_dependencies(main create_test2)

create_test1_test2.cpp

#include <fstream>
#include <iostream>

int main() {
  std::ofstream test1("test1.txt");
  test1 << "test1" << std::endl;
  test1.close();

  std::ofstream test2("test2.txt");
  test2 << "test2" << std::endl;
  test2.close();

  return 0;
}

main.cpp

int main() { return 0; }

I have a create_test1_test2 executable that will generate test1.txt and test2.txt. For productivity purposes, I want to be able to hand edit test1.txt in the IDE after it is being generated by create_test1_test2 and get the corresponding test2.txt. I could achieve the same thing by modifying create_test1_test2.cpp to recompile and regenerate the equivalent of the hand edited test1.txt and the corresponding test2.txt, but that would slow down development time quite a bit. I want to know how I can quickly hand edit test1.txt and invoke a much lighter weighted pre-compiled executable to generate the corresponding test2.txt via add_custom_command. The approach I showed in the minimal example is from How to configure cmake to recompile a target when a non .cpp source file is modified, but the approach only worked if test1.txt is in the source, it doesn't work if it's an intermediate file generated by an executable, meaning if I hand edit test1.txt, test2.txt doesn't get refreshed with a new make main nor a make create_test2 call. What should I change in order to make it work for this scenario?

user3667089
  • 2,996
  • 5
  • 30
  • 56
  • A note on style... you should almost never use `CMAKE_BINARY_DIR`. Much better is to use `CMAKE_CURRENT_BINARY_DIR`. This accounts for when your project is not the top-level, i.e. it has been in included in another project via `add_subdirectory` or `FetchContent`. – Alex Reinking Jan 10 '22 at 03:59

0 Answers0