Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CMake Run Built Executable Before Building Another?

Tags:

cmake

How would i tell CMake to build and run an executable before building another? So i have 2 executable files "a" and "b", where "a" is required to run in order to generate header files for "b". So "a" takes 2 folders as a parameter, in which it generates header files from xml files from an input directory to an output directory.

Is there a way to tell CMake to do this as well as to know when the xml files are modified or when project "a" is modified to regenerate the files?

like image 953
user3901459 Avatar asked Aug 21 '14 23:08

user3901459


1 Answers

If test1 being built from test1.c needs prior execution of test2 being built from test2.c, then the solution should look like this:

-- test1.c --

#include <stdio.h>
int main(void) {
    printf("Hello world from test1\n");
    return 0;
}

-- test2.c --

#include <stdio.h>

int main(void) {
    printf("Hello world from test2\n");
    return 0;
}

-- CMakeLists.txt --

cmake_minimum_required(VERSION 2.8.11)

project(Test)

set(test1_SOURCES test1.c)
set(test2_SOURCES test2.c)

add_executable(test1 ${test1_SOURCES})

add_executable(test2 ${test2_SOURCES})
add_custom_target(test2_run
  COMMAND test2
  WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
  COMMENT "run generated test2 in ${CMAKE_CURRENT_SOURCE_DIR}"
  SOURCES ${test2_SOURCES}
)

add_dependencies(test1 test2_run)

It generates the following output:

alex@rhyme cmake/TestDep/build $ cmake ..             
-- The C compiler identification is GNU 4.8.2
-- The CXX compiler identification is GNU 4.8.2
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Configuring done
-- Generating done
-- Build files have been written to: /home/alex/tmp/cmake/TestDep/build
alex@rhyme cmake/TestDep/build $ make test1
Scanning dependencies of target test2
[ 25%] Building C object CMakeFiles/test2.dir/test2.c.o
Linking C executable test2
[ 25%] Built target test2
Scanning dependencies of target test2_run
[ 50%] run generated test2 in /home/alex/tmp/cmake/TestDep
Hello world from test2
[ 75%] Built target test2_run
Scanning dependencies of target test1
[100%] Building C object CMakeFiles/test1.dir/test1.c.o
Linking C executable test1
[100%] Built target test1

You may also need to use add_custom_command and other related CMake directives if your task demands it.

like image 115
user3159253 Avatar answered Sep 25 '22 15:09

user3159253