How to determine where the title is included from

Is it possible to programmatically determine (and print) where the C ++ header was included from?

I have a headline like:

// DeprecatedHeader.h __pragma( message ("DeprecatedHeader.h is deprecated - include NewHeader.h instead.") ) #include "NewHeader.h" 

As you can see, the compiler is MSVC, but I have macros to port. GCC is welcome, but if this is not possible, I would enable the "trick" only on Windows.

But I am looking for a result, for example

 "AnyOtherFile.cpp was including DeprecatedHeader.h, please include NewHeader.h instead." 

Change To be clear why I want this: the warning that the compiler generates already helps a lot: the code is not broken, but causes people to change the include. Problem: He could blame the wrong β€œguy” as you could pull this heading through a different heading. My goal was to blame the error header, not the compilation unit.

+4
source share
3 answers

Despite the fact that I do not think it is worth using this functionality, but here is the solution.

At the top of each header file, after checking the obsolete 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 line.

So your headers will look like this (with gcc):

Regular title:

 #undef INCLUDING_FILE #define INCLUDING_FILE "normal.h" #include "deprecated.h" 

Deprecated heading:

 #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" 
+1
source

You can run your compiler with the ability to create pre-processed source code, and not fully compiled ( gcc -E , CL.EXE /E or any other). The resulting code will include the tagging from which each piece of code originates.

+2
source

Not sure about the exact solution (maybe it’s possible to do this with __FILE__ and other similar macros), but you can try the #warning preprocessor directive placed in the wrong header file. At compile time, it issues a warning that will notify you of what you want.

0
source

Source: https://habr.com/ru/post/1447695/


All Articles