execute_process and add_custom_target behave differently with respect to COMMAND

Dear CMake Folks, I have a strange issue, I need to run matlab script and use the generated code for compilation.
I would like to run matlab2018b(64 bit) in Windows without display and I am using MinGW as makefile generator.
For me this works without the display but is not intended (I need generation before build)

add_custom_target(generate_sources ALL COMMAND ${Matlab_MAIN_PROGRAM} -nosplash -nodesktop -noFigureWindows -minimize -wait -log -r "matlab_script"

While this works with matlab display:

COMMAND           "${Matlab_MAIN_PROGRAM}"  -nosplash -nodesktop -noFigureWindows -minimize -wait -log -r "matlab_script"
TIMEOUT           600
message("OUTPUT variable is: ${RES}")
if(NOT (RES EQUAL 0) OR STDERR MATCHES "\?\?\? Error")
message( FATAL_ERROR "execute_process returned ${RES}" )

I would like to use execute_process as it is meant during config time.
I suspect there is something in the way that I specify COMMAND in both cases.
Could you please help?

I am not exactly sure what the question is here. What are you trying to do at configure time and what are you trying to do at build time? What is not working?

HI Bill, Thanks for replying. Sorry if my earlier explanation was not clear enough. I would like to run a .m script at PRE BUILD step which I am using for generating code. I face the following issues:

  • If I use execute_process it is running twice , probably once at configure and once at build step. execute_process is also not making MATLAB work in headless mode. It pops up the MATLAB window which prevents it from running in an automated CI environment like jenkins.
  • If I use add_custom_target, it is triggered after BUILD step. It doesnot wait for MATLAB to finish.

What you want is a chain of custom commands/targets. This might help https://cmake.org/cmake/help/latest/guide/tutorial/Adding%20a%20Custom%20Command%20and%20Generated%20File.html. Basically you want the outputs of your .m script to be inputs to some other target and make sure the chain of depends is setup so things are run in the right order. I don’t think you want to do any of this with execute_process as that will only happen at configure time.

Hi Bill, Thanks for your suggestion. Now it did work just the way I wanted. However why it did not work with execute_process. In many places for example FindMatlab.cmake uses execute_process as well as cmake/MatlabTestsRedirect.cmake at master · RobotLocomotion/cmake · GitHub . Could you please explain why it works here and not in my use-case? Thanks!

In the link you sent that is for running Matlab tests at ctest time with a cmake -E script command. So it is not being done as part of the build at all.