villaa villaa - 10 days ago 6
Git Question

multiple commands in cmake execute_process

I have a project that I am using cmake to help build. The suppose the project is in

/home/proj
and the build directory is in
/home/proj-build


The
/home/proj
directory is a git repository with some tags, and I would like to incorporate the most recent tag into the code when it gets built so that the binary knows what version it is.

In my
CMakeLists.txt
file I have the following stanza in the setup portion:

set(CMAKE_BUILD_TYPE None)
message(${CMAKE_CURRENT_SOURCE_DIR})
execute_process(COMMAND cd ${CMAKE_CURRENT_SOURCE_DIR} && exec git describe --abbrev=0 --always OUTPUT_VARIABLE GIT_VERSION)
message("${GIT_VERSION}")
set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -D__GIT_VERSION=\\\"${GIT_VERSION}\\\"")
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -D__GIT_VERSION=\\\"${GIT_VERSION}\\\"")


The problem is that the compound command in the
execute_process
apparently returns an empty string for the version. I have to somehow run the
git describe
command from inside the repository directory, but it is distinct from the build directory where the code is getting made.

How can I get the make process to execute the appropriate git command in the appropriate directory, even when envoked from the build directory? Also, how can I get
cmake
to get the output from a compound command as I would normally expect in the shell?

Things I've tried

I've tried to surround the compound command with parentheses as suggested here in order to run the command in a sub-shell, but the output does not seem to be returned to the parent shell.

This link suggests that
execute_process
can be run with several
COMMAND
invocations, but it seems the
stdout
from the first is piped to
stdin
of the next, so that won't produce the desired result.

I also tried explicitly envoking the shell using
sh -c
inside the
execute_process
structure. I'm not sure I fully understood the results of this attempt but I could not get the
'
I would need in this situation to escape properly inside the
execute_process
.

Answer

Command execute_process has WORKING_DIRECTORY option, which intention is to set directory where COMMAND will be invoked:

execute_process(COMMAND  git describe --abbrev=0 --always 
    WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
    OUTPUT_VARIABLE GIT_VERSION
)

As for && operand, it doesn't work with execute_process, because shell isn't used for run the command. This is explicitely stated in documentation.

Normally, for achive sequential order of the commands, you need to call execute_process twice (or more). But such usage doesn't work with changing directory, that is why special option is introduced.

Comments