x-x
x-x

Reputation: 7515

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?

#include <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;
}

Upvotes: 3

Views: 3688

Answers (5)

Gerhard Stein
Gerhard Stein

Reputation: 1563

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;

Upvotes: 0

Erik
Erik

Reputation: 91300

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.

Upvotes: 3

Matteo Italia
Matteo Italia

Reputation: 126867

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.

Upvotes: 4

DigitalRoss
DigitalRoss

Reputation: 146141

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.

Upvotes: 0

Anycorn
Anycorn

Reputation: 51505

no, but:

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

Upvotes: 13

Related Questions