3

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;
}
0

5 Answers 5

13

no, but:

gcc -DCOMPILED_ON="$(uname -a)"
Sign up to request clarification or add additional context in comments.

Comments

4

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.

Comments

3

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.

Comments

0

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.

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.