Sergey
Sergey

Reputation: 170

How to print macros in msvc preprocessor?

Is there a way to see my #defines in preprocessor file using msvc or gcc?

here's a little code:

#include <iostream>

#define asdasdadda asdsad    

int main()
{
    #ifdef asdasdadda
        std::cout << "yes\n";
    #else
        std::cout << "no\n";
    #endif

    return 0;
}

I compile it with cl by this way:

$ cl main.cpp /C /P

And here's the tail of preprocessored main.i:

#line 2 "main.cpp"




int main()
{

        std::cout << "yes\n";


#line 13 "main.cpp"

    return 0;
}

And here's that I expect:

#line 2 "main.cpp"


#define asdasdadda asdsad

int main()
{

        std::cout << "yes\n";


#line 13 "main.cpp"

    return 0;
}

gcc behaviour is the same...

Upvotes: 3

Views: 1958

Answers (2)

James McNellis
James McNellis

Reputation: 355297

There is an undocumented compiler switch, /d1PP, that will retain macro definitions in the preprocessor output. If you compile Rado's example with /P /d1PP, you'll get the following output file:

#line 1 "q.cpp"
#define BLAH 1

int main()
{

      cout << "BLAH defined" << endl;


#line 10 "q.cpp"
}

Note that this switch is not documented. It is thus not officially supported. It may be removed at any time, or its behavior may be changed at any time. It may have bugs. Use at your own risk, etc., etc.

Upvotes: 11

Rado
Rado

Reputation: 8973

Don't think that MSVC supports this, but with gcc or clang, use -dD option. See Options Controlling the Preprocessor for more information. Specifically:

-dCHARS

M Instead of the normal output, generate a list of #define directives for all the macros defined during the execution of the preprocessor, including predefined macros. This gives you a way of finding out what is predefined in your version of the preprocessor. Assuming you have no file foo.h, the command

touch foo.h; cpp -dM foo.h

will show all the predefined macros.

D Like M except in two respects: it does not include the predefined macros, and it outputs both the #define directives and the result of preprocessing. Both kinds of output go to the standard output file.

Example:

#define BLAH 1

int main()
{
#ifdef BLAH
      cout << "BLAH defined" << endl;
#else 
      cout << "undef" << i << endl;
#endif
}

g++ -E -dD q.cpp produces:

# 1 "q.cpp" 2
#define BLAH 1

int main()
{

      cout << "BLAH defined" << endl;



}

Upvotes: 1

Related Questions