Reputation: 1784
I am looking for ways to visualize the effects of #define's - For example that code not seen by the compiler is shown in a different color.
Primarily visual studio, but nice to know about other environments? Ideally, also code seen by the compiler, but will not be run.
Upvotes: 1
Views: 324
Reputation: 1
How can i visualise C/C++ #define's?
Short answer: in general you cannot (and notice that you don't define what "visualize" means in your question). You really want to look at the preprocessed form. With GCC you practically get it with gcc -C -E
.
As a provocative example, __TIME__
or __LINE__
is a preprocessor magic predefined macro (and so is the __COUNT__
which is a GCC extension). You are allowed to code
#if __LINE__ % 2 == 0
printf("hello from line %d\n", __LINE__);
#endif
and the behavior depends upon where that weird code is located (on an even-numbered line, or an odd-numbered one).
Ok, that example is contrived, but legal. Check by reading the C11 standard n1570.
You could also imagine some #if __TIME__[1] == '2'
but probably that won't compile (because preprocessor expressions cannot use the []
indexing). However, some if (_TIME__[5] == '2') printf("hello\n");
would compile (and be optimized differently, depending on the moment you are compiling it).
And in practice, code nearly as contrived as the one above does exist. A good example of C code using a lot various preprocessor features is the Linux kernel source code (you might be interested by coccinelle, a tool knowing that). The first step of its build (using make config
or make menuconfig
) generates a lot of headers defining the features of your particular kernel. There are many thousands of such configuration options (my /boot/config-4.19.0-3-amd64
has 7352 configuration choices, and each of them translates to some preprocessor macro used in #if
).
Upvotes: 1
Reputation: 23701
Visual Studio does this already by default, at least since VS2005 and much better since VS2010 (going by this Q/A):
Edit: Added in response to another answer:
Upvotes: 3
Reputation: 32596
One way is to see the source after the preprocessing, using gcc (for C) or g++ (for c++) just use the option -E
For instance having the file p.cc
#ifdef FOO
# define BAR 1
#else
# define BAR 2
#endif
int main()
{
return BAR;
}
if I do without defining FOO I have :
/tmp % gcc -E p.cc
# 1 "p.cc"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "p.cc"
int main()
{
return 2;
}
if I do defining FOO I have :
/tmp % gcc -DFOO -E p.cc
# 1 "p.cc"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "p.cc"
int main()
{
return 1;
}
Note : you probably have #include
in your source so after the preprocessing you get a lot of lines coming from the included files, for the question How to show 'preprocessed' code ignoring includes with GCC I put an answer to bypass them.
Upvotes: 9