c++ - #ifdef macro - c++

I can see
#ifdef <token>
code;
#endif
to be included, but I can't find it defined in any of the headers it includes. Is there any other mechanism with which the token could be defined?

Firstly, there are macros that are implicitly defined by the compiler (for example, __cplusplus). Some of these are standard, and some are compiler-specific extensions. See your compiler manual for the full list.
Additionally, most compilers allow defining macros on the command line. The exact mechanism is compiler-dependent, but often takes the form of a -D or /D command-line option. For example, see the gcc manual:
-D name
Predefine name as a macro, with definition 1.
-D name=definition
The contents of definition are tokenized and processed as if they appeared during translation phase three in a `#define' directive. In particular, the definition will be truncated by embedded newline characters.
If you are invoking the preprocessor from a shell or shell-like program you may need to use the shell's quoting syntax to protect characters such as spaces that have a meaning in the shell syntax.
If you wish to define a function-like macro on the command line, write its argument list with surrounding parentheses before the equals sign (if any). Parentheses are meaningful to most shells, so you will need to quote the option. With sh and csh, -D'name(args...)=definition' works.
For Microsoft Visual C++, see http://msdn.microsoft.com/en-us/library/hhzbb5c8(v=vs.80).aspx
Some compilers provide convenient tools for figuring out where a particular preprocessor macro is defined. See, for example, How to know (in GCC) when given macro/preprocessor symbol gets declared?

Most (all?) compilers allow defining values with flags (-D in gcc), also some may be set by the compiler itself.

Yes, of course, preprocessor directives can be set with the compiler. For example, gcc lets you add directives in the command line, you can specify directives in the project settings in Visual Studio. Also think about __cplusplus, or _LINE_ of _FILE_. Those aren't defined anywhere, yet they exist. Also _DEBUG or UNICODE which are set up by the MSVS environment.

Related

use cppcheck without defining all the macros

I use cppcheck on a project using the boost library. The headers in this library contain a huge amount of macro that I don't even use in my sources. Nevertheless, cppcheck explore paths depending on these macros that I think useless. Is there a way to tell cppcheck to ignore all macros unless it's defined in a source code using a #define?
Here is the the necessary part from cppcheck documentation:
-D<ID> Define preprocessor symbol. Unless --max-configs or
--force is used, Cppcheck will only check the given
configuration when -D is used.
Example: '-DDEBUG=1 -D__cplusplus'.
-U<ID> Undefine preprocessor symbol. Use -U to explicitly
hide certain #ifdef <ID> code paths from checking.
Example: '-UDEBUG'
You are able to define (-D) or undefine (-U) custom preprocesser symbols with these options.
Another option that is potentially interesting is
-f, --force Force checking of all configurations in files. If used
together with '--max-configs=', the last option is the
one that is effective.
and
--max-configs=<limit>
Maximum number of configurations to check in a file
before skipping it. Default is '12'. If used together
with '--force', the last option is the one that is
effective.
This means the following:
cppcheck --force <PATH_TO_YOUR_CODE>
Cppcheck verifies all combinations of preprocessor paths, which could lead to long checking times on large code bases.
The corresponding documentation can be found here.
Not exactly what you want, but you can specify define to cppcheck so it evaluates only one branch:
see -D/-U options.
One option is to ignore lines with missing macros by putting this comment above the offending line:
// cppcheck-suppress unknownMacro
Use --config-exclude= to exclude the directories that contain unmanageable configurations. It only excludes header files.

Documenting preprocessor options with Doxygen

I have a C++ package that allows for different behavior if the user defines different pre-processor constants. For example, a user can use /D ALLOW_WIDE_CHAR in the makefile to change the behavior to support wide characters.
I would like to document these options with Doxygen, but Doxygen complains because there is no actual #define in the code. It is up to the user to do that.
Adding the definition to the PREDEFINED list in the configuration file doesn't help.
Suggestions?
One option I found is to create an extra source file, say Doxygen.h, that is not compiled, but is added to the Doxygen file list. This file can use #define to define those pre-processor constants. It seems like there should be a better solution, though.

Preprocessor keeping macros

I want to preprocess C++ header files keeping all macros verbatim in the output text.
For that, I need a C preprocessor-like program that performs these tasks:
store in memory macros from #define directives;
recursively follow #include directives;
evaluate conditions in #if and #ifdef directives;
suppress the code in inactive portions of #if .. #else .. #endif blocks;
(optionally) remove /* .. */ and // comments;
remove all remaining directives lines.
But the macros must not be replaced in the output. Or alternatively, the preprocessor may take in argument a list of macro names that shall not be replaced.
This may sound weird, but I have a good reason for that. I have a series of Perl scripts able to analyze preprocessed C++ class headers. And I use some macros to tell them for example which methods to export.
I haven't found a preprocessor program able to perform what I need, so I wrote a Perl
script. The latter actually works, but is slow and non standard. I am looking for a better alternative.
Use gcc -E to run the preprocessor manually. This will expand all the macros but that's not a problem.
What you want is special macros for the time when you need the output for your Perl scripts. Try this:
#ifdef PERL_PREPROCESSING
# define EXPORT(...) PERL_EXPORT
#else
# define EXPORT(...) ...normal C code...
#endif
So the idea is that you call gcc -E -DPERL_PREPROCESSING to switch some of the macros to produce output that your perl scripts can locate. The macros will be expanded as usual.
[EDIT] If you don't want to pollute your sources with Perl-specific macros, use this trick: Create a folder which contains the header file with the Perl versions of the macros and include this folder before every other folder with -I. gcc will then ignore the standard header file.
If you are using *nix you can use the grep command to find all the #defines in the directory
grep -R . '#define'
For the preprocessing required, use gcc -E.

How to figure out what value MSVC is using for a preprocessor macro

I'm attempting to use a /D compiler option on MSVC6 to define a string, but there's something weird about using double quotes around it. To debug this problem, it would be extremely helpful for me to be able to see what value the preprocessor is actually substituting into my code where the macro is expanded. Is there any way I can do this? I tried creating a Listing file with "assembly and source", but the source contains the original macro name and the ASM is some incomprehensible gibberish at that line. Is there a way to get the macro value at compile time?
Failing that (or perhaps more useful), how do I specify a string with the /D option? It needs to substitute into my source with double quotes around it, since I'm using it as a string literal.
Try one of the following options to CL.exe:
/E preprocess to stdout
/P preprocess to file
If you're building within Visual Studio, you can specify custom command-line options in one of the project property dialogs.
MSVC has a compiler flag that allows you to see the preprocessed source file with all the macros expanded, comments removed, etc. - the entire translation unit in terms of the actual code that will compile. Preprocessed output should give you the insight you're looking for regarding your macro expansion. More info here.
There's an option to pass to the compiler (/P) and it will write the preprocessor output into my_cpp_file.i where you can look at it.

Viewing compiler expanded code - C++

I learned that compiler will expand macros while compiling. Templates are also expanded at the compile time. Is there any way to see this expanded code? I am compiling using Visual Studio 2008.
any thoughts?
The VC++ compiler (cl.exe) supports a few command line switches for this:
/E preprocess to stdout
/P preprocess to file
/EP preproscess to stdout with no #lines
Additional command-line switches can be added in your project properties. In my version (VC2005), Configuration Options -> C/C++ -> Command Line -> Additional Options
The compiler doesn't actually do any of the macro expansion. That is the task of the pre-processor. It all appears as one step, but the compiler actually forks out to a separate pre-processor tasks and traps the output for you.
Templates are not "expanded" at compile time. They are instantiated on use during compile. The difference is that the compiler immediately generates object code for the template; there's no intermediate source code that comes out. You can't look at the instantiated template code as source, it's dumped out as assembly when it's needed.
If you have GCC you can also call the pre-processor directly using 'cpp' with the right arguments (mostly include paths and command line macro definitions). Others have answered for MSVC.
Note that /E in VC++ only expands preprocessor statements (that is, #include, #ifdef, #define etc.)
I am not aware of any modern compiler that allows to expand templates.
To emit the preprocessed code, call cpp directly of use the -E option in gcc and related compilers; I'm sure other compilers or suites have similar things (indeed as per the other answer it's /E or /P in VC++).
Not sure about outputting instantiated templates. That's much harder to do, I think, since it's actually part of compilation rather than preprocessing (at least in modern compilers, since the original cfront version which was a c++-to-c translator, if I recall correctly).
It's easy to add an option to compilers to show the output after macro substitution. That's defined as a simple text substitution option anyway. Many compilers implement this as a separate stage, sometimes even handled as a separate tool. In any case, the result of the macro substitution is a collection of Translation Units in text form.
Templates, on the other hand, are compiled. There are multiple stages to this. Names are resolved twice, for instance. In either stage, the compiler would store the result of the name lookup. That's a table entry. How would you show that in text form? There's no trivial C++ expression for that.