简体   繁体   中英

Including constants without importing header file

I have a piece of code set up to take a constant integer parameter (dimension of the problem), but it could run with many different dimensions.

I don't want to have to change the hard-coded dimension every time I run, I would ideally define several dummy header functions that are basically just:

#ifndef dim_define_h 
#define dim_define_h 

    const int dimension = [DIMENSION SPECIFIC TO THIS HEADER FILE];

#endif

Then when compiling I could use whichever header file I needed for that instance like:

g++ dimension_6.h code.cpp

Is such a thing possible? Defining a constant in a header file and using it in another file that doesn't explicitly import that header file?


EDIT:

My next attempt was to take the main function only, stick it along with the dimension definition in a different file, and make copies of that. Then the compilation looks like:

g++ dim_specific_main.cpp lots.cpp more.cpp helpers.cpp

And I think it's making it through the compilation of main now, which depend on helper functions defined in all the helper files. Unfortunately when it tries to compile the helper functions it needs the constant that's defined in main.h and it seems to have forgotten it.

EDIT 2: I realize now that I'm trying to use this variable in places where it needs to be known at compile time, and I think that the linkage happens after compiling, so I do not believe this particular approach is possible.

const int dimension = THE_DIMENSION;

then compile with

g++ -DTHE_DIMENSION=6 code.cpp

No header needed.

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