How do I show the value of a #define at compile time in gcc

15,293

Solution 1

To display macros which aren't strings, stringify the macro:

#define STRINGIFY(s) XSTRINGIFY(s)
#define XSTRINGIFY(s) #s

#define ADEFINE 23
#pragma message ("ADEFINE=" STRINGIFY(ADEFINE))

If you have/want boost, you can use boost stringize to do it for you:

#include <boost/preprocessor/stringize.hpp>
#define ADEFINE 23
#pragma message ("ADEFINE=" BOOST_PP_STRINGIZE(ADEFINE))

Solution 2

I'm not sure if this will do what you want, but if you're only interested in this to debug the occasional macro problem (so it's not something you need displayed in a message for each compile), the following might work for you. Use gcc's -E -dD option to dump #define directives along with preprocessing output. Then pipe that through grep to see only the lines you want:

// test.c
#include <stdlib.h>
#include <stdio.h>
#define ADEFINE "23"
#include <string.h>

int main(int argc, char *argv[])
{
#undef ADEFINE
#define ADEFINE 42
    return 0;
}

The command gcc -E -dD -c test.c | grep ADEFINE shows:

#define ADEFINE "23"
#undef ADEFINE
#define ADEFINE 42
Share:
15,293

Related videos on Youtube

John Lawrence Aspden
Author by

John Lawrence Aspden

Programmer/Contractor/Consultant in Cambridge UK Lover of LISP, C and Unix. Friend of Python and ML. CV: http://www.aspden.com Clojure Blog: http://www.learningclojure.com Random Thoughts: http://johnlawrenceaspden.blogspot.com

Updated on June 14, 2022

Comments

  • John Lawrence Aspden
    John Lawrence Aspden almost 2 years

    So far I've got as far as:

    #define ADEFINE "23"
    #pragma message ("ADEFINE" ADEFINE)
    

    Which works, but what if ADEFINE isn't a string?

    #define ADEFINE 23
    #pragma message ("ADEFINE" ADEFINE)
    

    causes:

    warning: malformed ‘#pragma message’, ignored

    Ideally I'd like to be able to deal with any value, including undefined.

  • John Lawrence Aspden
    John Lawrence Aspden about 12 years
    Well, I don't think my client is going to be very happy to have that added as a dependency, but that looks like an existence proof. Perhaps I should go and have a look at stringize.hpp
  • rob05c
    rob05c about 12 years
    @JohnLawrenceAspden I updated the answer with how to do it without boost (or any other library).
  • Paul
    Paul over 5 years
    Your link is no longer active: "stringify the macro"