简体   繁体   中英

How to include part of file by C++ preprocessor #include

I want to refer some stable library code which is not maintained by me. Actually it is some MFC code snippet.

But, whenever I want to include the code snippet, I have to #include entire file, which consequently I have to include other stuff, then the whole MFC ... The consequence is not acceptable.

Currently, I copy/paste the code snippet into my project, but I feel disgraceful. Can I just refer part of a file by C++ preprocessor?

Even the code is hard-linked with specific MFC version, it is better than duplicate them in my project. With such hard-link, I will know it's from MFC and save my time to check them.

Is there some super #include usage?


Can we write something like

#include  "foo.h" line [12, 55)

which means to include line 22 to 54 for foo.h

What some have done is write #ifdef-sections in their headers to allow including files to only get specific parts. I don't know if your MFC file has those but you can look through it and use any existing ones or write your own.

The header usually look something like this

#ifdef USE_FANCYPANTS
bool hasFancyPants();
#endif

#ifdef USE_COOLSTUFF
void doCoolStuff();
#endif

And your include files then use #define before including.

#define USE_FANCYPANTS
#include "header.hpp"

Then you only get hasFancyPants() and not doCoolStuff()

  • You can use conditional compilation to inlcude/exclude stuff you dont need. You have to change the source code slighty, and amend project settings.
  • Can use typedef keyword, which would define types differently for MFC and non-MFC, and/or specific to your project settings, and the legacy code.
  • You may put entire stuff in a DLL or a .LIB (having code, not just declaration), and put the linker pragma in header file itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM