开发者

Can the gcc C preprocessor use the output of a shell command?

For example, can the output of 'uname -a' be used to create the COMPILED_ON macro below?

#includ开发者_运维技巧e <stdio.h>

#define COMPILED_ON `call uname -a and use the output as a quoted string'

int main( int argc, char **argv ) {
    printf( COMPILED_ON );
    return 0;
}


no, but:

gcc -DCOMPILED_ON="$(uname -a)"


I don't think that you can do that with the GNU preprocessor, but surely it's not doable with a plain standard preprocessor; instead, I think that this is the job for the Makefile.

Let it run uname -a and store it in a Makefile variable, that will be used to create the correct -D directive for the compiler.

You could also make the Makefile create a .h file that will contain the macro definition, and that file will be #included by the files that need the COMPILED_ON macro. This has the extra bonus of being independent of compiler-specific options to define macros.

Notice that these suggestions are applicable also to build tools other than the good ol' make.


Not like that, no.

You'd need to do:

gcc "-DCOMPILED_ON=\"`uname -a`\"" -c file.c -o file.o

Alternatively, have your makefile create a simple .h file:

echo "#define COMPILED_ON \"`uname -a`\"" > compiledon.h

Then #include "compiledon.h"

You'll need the \" part in order to get a usable string.


No, but you can achieve your objective in a less fragile and SCCS-hostile manner.

  1. Have a make target run a shell script to create a .h file.

  2. Have a make variable set itself via a shell command and pass down a -D. Not all make(1) implementations support this.

  3. Have your make target run the compiler with a -D that incorporates the shell command.


If you happen to use CMake I have a nice snippet that might help some:

# This ensures the SHA1 git ref is shown within the app
execute_process(COMMAND git rev-parse HEAD WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} OUTPUT_VARIABLE GITSHA1REF)
string(REGEX REPLACE "\n$" "" GITSHA1REF "${GITSHA1REF}")
message(STATUS "GITSHA1REF = ${GITSHA1REF}")
add_definitions("-DGITSHA1REF=\"${GITSHA1REF}\"")

With that I get the current Git SHA1 hash and use it like this in my C++ code:

std::cout << "Git-SHA1: " << GITSHA1REF << std::endl;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜