0

I wanna run a bash script using cmake. And I am partially successful. I am not understanding the workflow properly.

main.cxx

# include <iostream>

int main()
{
    std::cout << "hello\n";
}

script.sh

#!/bin/bash
touch file;

CMakeLists.txt

cmake_minimum_required(VERSION 3.21.1)
project(testdir)

add_executable(mainbin "main.cxx")

add_custom_command(TARGET mainbin
    POST_BUILD
    COMMAND /bin/sh /path/to/testdir/script.sh
)

So, this is my directory tree.

testdir
   |
   |---CMakeLists.txt
   |
   |---main.cxx
   |
   |---script.sh

When I do "cmake . ; make ;", cmake runs the bash script and except the cmake build related files, the directory tree looks like this:

testdir
   |
   |---file
   |
   |---CMakeLists.txt
   |
   |---main.cxx
   |
   |---script.sh

So it worked. But now I would want to rename "file" to "renamed_file". So I would edit script.sh. New script.sh looks like this:

#!/bin/bash
mv file renamed_file;

Now when I do "cmake . ; make ;" again, it doesn't work. I mean file "file" doesn't change to "renamed_file". I wanna run script.sh everytime I call "cmake . ; make ;".

Maybe I am missing a very simple thing/basic understanding. What should I do to achieve that?

SuperNoob
  • 170
  • 1
  • 10
  • CMake isn't checking the contents of your script and won't run it as as far as it is concerned nothing has changed. Delete the cache and files and it will run again. – Dorito Johnson Aug 24 '21 at 15:34
  • @Dorito Johnson Yeah but is there any other way to tell cmake that "something" has changed? Is there any way so that cmake checks if script.sh has changed or not everytime before building? – SuperNoob Aug 24 '21 at 15:45
  • `add_custom_command` implies to be used to run a COMMAND **conditionally** (after some files are changed). If you want to run a COMMAND unconditionally, then use `add_custom_target`. See [duplicate question](https://stackoverflow.com/questions/13920072/how-to-always-run-command-when-building-regardless-of-any-dependency) for more info. – Tsyvarev Aug 24 '21 at 17:50

1 Answers1

0

As you want to keep track of the content of the script, adding it as a source of a custom target will keep track of its mtime and copy it to the build directory if changed. Something like this will help you to achieve that.

add_custom_target(myscript
    COMMAND /bin/sh /path/to/testdir/script.sh
    SOURCES /path/to/testdir/script.sh
    )

Disclaimer, I have not tried it, you night need to iterate on this.

More info: https://cmake.org/cmake/help/latest/command/add_custom_target.html

Vicente Bolea
  • 1,409
  • 16
  • 39