Preprocessor in visual studio 2010-c++ project - c++

In .cpp file I use a macro mmData1.I searched in the project and see that this macro is defined in several files.(I.e. there are several .h files which have the line #define mmData1)
I want to know if there is a capability in VS10 to check from which file the preprocessor takes the macro value

If Intellisense does not know then there is no direct way. However, there are indirect ways. Say your macro name is SOME_MACRO
After each instance of #define SOME_MACRO put #error Defined here, then right click the source file and choose Compile. If compiler returns an error remove the directive that raises it and compile again. The last instance of this error will tail the definition visible in the source.
Make each directive defining SOME_MACRO define it as something else and then, in the source file, add these lines after all includes:
#define STRINGIZE(x) STRINGIZE2(x)
#define STRINGIZE2(x) #x
#pragma message("SOME_MACRO is expanded as: " STRINGIZE(SOME_MACRO))
Compile the source file; you should see the value in the build log.
Less intrusive way: put those lines after each #define SOME_MACRO
#pragma push_macro("STRINGIZE")
#pragma push_macro("STRINGIZE2")
#define STRINGIZE(x) STRINGIZE2(x)
#define STRINGIZE2(x) #x
#pragma message("Defining at " __FILE__ ":" STRINGIZE(__LINE__))
#pragma pop_macro("STRINGIZE")
#pragma pop_macro("STRINGIZE2")
Or, if you don't need the line number:
#pragma message("Defining at " __FILE__)
Compile the file. Looking at build log you should be able to tell the order of SOME_MACRO definitions.

The best way to see exactly what the preprocessor is doing is to inspect its output directly. Intellisense is helpful but often does not match what the compiler understands.

A simple trick I always use is to redefine the macro at the line you want to check. When you compile the code, the preprocessor will complain and tell you where the previous definition was.
Example:
test.cpp contains:
#include "test.h"
int main()
{
#define SOMEMACRO 1
return 0;
}
test.h contains:
#define SOMEMACRO 2
int foo();
when compiling test.cpp, I get this error message:
test.cpp:5:0: warning: "SOMEMACRO" redefined [enabled by default]
In file included from test.cpp:1:0:
test.h:1:0: note: this is the location of the previous definition
I tested on GCC, but Visual Studio does the same thing.

Related

Should we include a macro(#define) in both .h & .cpp files

If i use them in both the files.
Going with the term "macro" in c++ it's just a replacement mechanism(doesn't know anything about c++ structure) that happens in pre-compilation stage.
Is this the reason that i should define macro(#define) in both the files or doesn't need to do that or am i missing anything.?
Defining the macro in the .h file and then just including that .h file in the .cpp file is good enough.
Assume a simple case first. You have the .cpp file using the .h file:
Car.cpp
Car.h
If you have a constant, say: #define KM_PER_MINUTE 3. If this constant is used by any function inside the .h file, put this #define in the .h file:
Inside Car.h:
#ifndef CAR_H
#define CAR_H
...
#define KM_PER_MINUTE 3
...
int calculate_total_KM(int minute)
{
return minute * KM_PER_MINUTE;
}
...
#endif
On the other hand, if this constant is used only in the .cpp file, put this #define in the .cpp file:
Inside Car.cpp:
#define KM_PER_MINUTE 3
...
int calculate_total_KM(int minute)
{
return minute * KM_PER_MINUTE;
}
...
From the documentation:
The #define directives define the identifier as macro, that is instruct the compiler to replace all successive occurrences of identifier with replacement-list, which can be optionally additionally processed. If the identifier is already defined as any type of macro, the program is ill-formed unless the definitions are identical.
I guess it fully replies to your question.
It goes without saying that you can define a macro in a .h file, then include it wherever you need that macro.
If you put it in #ifndef then it doesn't matter, it will be included only once (the first occurrence). I you doesn't, then you'll get warning for already defined macro when the macro defined in the source and also the header with the macro included.
BTW: There is a third place, you can declare the macro in the makefile, or project settings.
'define macro(#define) in both the files' cause redefinition error or warning.
It's not good. It may cause program compile error(good thing), or runtime error(terrible thing).

Get current compilation unit name within #include

My current goal is to create one (or as few as possible) line of code that will switch the remainder of the active compilation unit to an unoptimized, debug configuration. My first instincts were either:
FORCE_DEBUG;
// code below here will be forced to be unoptimized and in a debug environment
or
#include "ForceDebug.h"
// code below here will be forced to be unoptimized and in a debug environment
would be ideal. In my workspace, to convert to an unoptimized debug configuration requires I change the pragma optimize level, but also #undef some macros and #define other macros.
The FORCE_DEBUG macro doesn't work because it would need to execute preprocessor directives #undef and #define which I understand are not evaluatable within a macro.
Instead I have a working version of #include "ForceDebug.h". But I want to message the developer that they have disabled optimization on a given compilation unit (so they don't check it in, or if they do check it in that it can be caught and fixed). Ideally this message includes the filename of whichever file #includes "ForceDebug.h" or the current compilation unit.
Here's an approx ForceDebug.h
#pragma once
#pragma message("DISABLING OPTIMIZATION IN" COMPILATION_UNIT_FILE)
#undef _RELEASE
#define _DEBUG
#ifdef _MSC_VER
# pragma optimize("", off)
#else
# pragma GCC optimize("O0")
#endif
So a call site would look something like Foo.cpp:
// this messages "ForceDebug.h", I want to message "Foo.cpp"
//#define COMPILATION_UNIT_FILE __FILE__
// double macro also messages "ForceDebug.h"
//#define COMPILATION_UNIT_FILE COMPILATION_UNIT_FILE2(__FILE__)
//#define COMPILATION_UNIT_FILE2(x) x
// this works but requires doing it manually, which I'm trying to avoid
#define COMPILATION_UNIT_FILE "Foo.cpp"
#include "ForceDebug.h"
// code below here will be forced to be unoptimized, debug environment
I can't use __FILE__ because that messages about ForceDebug.h, when I want it to report about Foo.cpp.
If I could evaluate __FILE__ inside Foo.cpp and pass the evaluated version into ForceDebug.h that would be acceptable, but I tried recursive macro calls and it still reported ForceDebug.h
Is there any way to get it to pass "Foo.cpp" into the include or to derive that value by some other means for either clang or Visual Studio?
I was not able to find a way to emit the current compilation unit name from an included file.
However, your proposed syntax requires the user of "ForceDebug.h" to add another directive to expose its compilation unit name to the header file. Instead, you can turn it around and allow simple inclusion that defines a macro that allows for the message to be emitted.
While, generally speaking, macros cannot be used to generate pre-processor directives, there is a syntax for pragmas for the compilers you illustrated. MSVC and GCC each have their own syntax, but conditional compilation can make the syntax appear uniform.
In your source file:
#include "ForceDebug.h"
FORCE_DEBUG;
//... rest of source
In "ForceDebug.h":
#pragma once
#ifdef _MSC_VER
#define DO_PRAGMA(X) __pragma(X)
#define NO_OPT optimize("", off)
#else
#define DO_PRAGMA2(X) _Pragma(#X)
#define DO_PRAGMA(X) DO_PRAGMA2(X)
#define NO_OPT GCC optimize("O0")
#endif
#define FORCE_DEBUG \
DO_PRAGMA(message("DISABLING OPTIMIZATION IN " __FILE__)) \
DO_PRAGMA(NO_OPT) \
struct __force_debug
#undef _RELEASE
#define _DEBUG
You could use the __FILE__ predefined macro like below:
#pragma message("DISABLING OPTIMIZATION IN " __FILE__)
Live Demo
Edit:
Since you want to report about the .cpp file I would go the other way around. That is, I would change ForceDebug.h to:
#pragma once
#undef _RELEASE
#define _DEBUG
#define OPT_OFF
^^^^^^^^^^^^^^^
#ifdef _MSC_VER
# pragma optimize("", off)
#else
# pragma GCC optimize("O0")
#endif
And then I would put the potensial message in my .cpp file:
#include "foo.h"
...
#ifdef OPT_OFF
#pragma message("DISABLING OPTIMIZATION IN " __FILE__)
#endif

How to detect where a header is included from

Is it possible to detect (and print out) programmatically where a C++ header got included from?
I have a header like:
// DeprecatedHeader.h
__pragma( message ("DeprecatedHeader.h is deprecated - include NewHeader.h instead.") )
#include "NewHeader.h"
As you can see, compiler is MSVC, but I have macros to wrap. GCC is welcome, but if not possible, I would enable the 'trick' just on Windows.
But what I'm looking for is an output like
"AnyOtherFile.cpp was including DeprecatedHeader.h, please include NewHeader.h instead."
Edit: To be clear why I want this: The warning the compiler throws is helping already a lot: the code is not broken but pokes the people to change the include. Problem: it may blame the wrong 'guy' as you could pull in this header via another header. My objective was to blame the erroneous header, not the compilation unit.
You can run your compiler with the option to produce the preprocessed source code rather than the fully compiled (gcc -E, CL.EXE /E or whatever) . The resulting code will include tagging of where each snippet of code comes from.
Even though I don't think it's worth pursuing this functionality, but here's a solution.
On top of each header file, after checking for deprecated header and before including other files, put this:
#undef INCLUDING_FILE
#define INCLUDING_FILE "file_name.h"
This can be done with a simple bash script where for each .h file you write this, including the file name in the string.
So your headers would look like this (with gcc):
Normal header:
#undef INCLUDING_FILE
#define INCLUDING_FILE "normal.h"
#include "deprecated.h"
Deprecated header:
#ifdef INCLUDING_FILE
# pragma message "Internal bug: " INCLUDING_FILE " included " __FILE__ " which is deprecated"
#else
# pragma message "Note: you shouldn't included " __FILE__ " which is deprecated"
#endif
#undef INCLUDING_FILE
#define INCLUDING_FILE "normal.h"
#include "others.h"
Not sure about an exact solution (probably it is possible to do with __FILE__ and other similar macros), but you could try #warning preprocessor directive placed into a wrong header file. During compilation it will issue a warning, which will notify about whatever you want.

Macro definition conflict

I'm running into this issue. This is not about macro functions, just simple string-value macro replacement.
I have two header files
test1.h
#define TEST 123
test2.h
#define TEST 456
Now I have a program included both these two headers, but I want my actually TEST to be 123.
How can I avoid defining TEST as 456?
You might think I'm crazy not to simply change the macro, but the situation is: I have a third-party decoder, which has this macro (defined in test1.h), and there's another WINAPI macro (defined in test2.h). Both of these files are controlled by others; I should not change either of them.
I don't need the test2.h at all, but I guess it's implicitly included by some other WINAPI header.
So, could anyone please tell me how to work around this issue? To overwrite the WINAPI macro with my third-party macro? Or how to nullify the definition from the WINAPI header in my own code? Is there a way to specify which header I don't want to include.
You can use the #ifdef pre-processor directive to determine if TEST is defined already for your particular case. Or just #undef it first.
#undef TEST
#define TEST 123
Put that in your header file where you want TEST to be 123 and not 456. Also, this needs to be before test1.h.
#undef TEST after the include of test2.h and before the include of test1.h. This is a bit of a hack though since you can't fix the macro names.
You can undefine it if you include both headers to your file as:
//yourfile.cpp
#include "test2.h" //include this before test1.h
#undef TEST //this undefines the macro defined in test2.h
#include "test1.h" //now this defines a macro called TEST which you need
#ifdef TEST
#undef TEST
#define TEST 123
#endif
Try this:
#include "test2.h"
#undef TEST
#include "test1.h"
This first includes test2, discards its TEST and then includes test1.

redefinition c++

how does header including in c++ work? I have the classes already implemented in .h file and when there is #include in two files, there's this error:
files.h:14:7: error: redefinition of ‘class abstract_file’
files.h:14:20: error: previous definition of ‘class abstract_file’`
multiple times for each class and enum.
Can anyone explain this?
Using include in C++ simply takes the file included and splats the contents into where it is included. To do this without worrying about multiple includes of the same file, you want to use header guards. Use this basic format for all header files:
#ifndef FILENAME_H
#define FILENAME_H
class foo (or whatever else is in the file!) {
...
};
#endif
You can only include a definition one time but headers can be included multiple times. To fix that, add:
#pragma once
to the top of each header file.
While #pragma once is relatively common, if you are using an older compiler it may not be supported. In that case, you need to fall back on manual include guards:
#ifndef MY_HEADER_H
#define MY_HEADER_H
...
#endif
(note that you need to replace MY_HEADER_H with a unique string for each header file)
header files usually define a unique symbol so that they are only included once.
e.g.
#ifndef _myheader_h
#define _myheader_h
// rest of header goes here
#endif
Some compilers support
#pragma once
See Pragma Once on wikipedia.
While many people have solved your error for you, it seems that nobody has answered your initial question:
how does header including in c++ work?
When the preprocessor finds an #include directive it replaces it by the entire content of the specified file.
You can read more on preprocessor directives at cplusplus.com.
Update: To illustrate this, you could try the following if you have gcc handy:
echo '#include <iostream>' > test.cxx
gcc -E test.cxx
You'll see the contrents of iostream whizz past your eyes as the preprocessed source code is sent to standard output.
What you can do is to guard your header from multiple inclusions:
#ifndef MY_HEADER__
#define MY_HEADER__
/* your stuff goes here! */
#endif
You can also use:
#pragma once
but it is not standard although it is supported by many compilers.
Use include guards in header files:
#ifndef FILES_H
#define FILES_H
struct foo {
int member;
};
#endif // FILES_H
This makes sure that your header will only get included once.
Another method is to use #pragma once in your header files, but it's not standard C. It's supported by Visual C, GCC and Clang though, so most likely it's ok to use.