Ad

How Do I Set Constants At Run-time In A C++ Header File, Imported Through Cython?

- 1 answer

I have some C++ code that currently relies on hard-coded constants, which are imported into multiple other cpp files, and I would like my python (pyx) file to set the constants once at runtime.

So, cython.pyx imports files a.cpp, b.cpp, and c.cpp, and constants.hpp

Files a.cpp, b.cpp, and c.cpp all import constants.hpp.

I would like instead to have one universal constants file, eg new_constants.yml, which python imports and sends through to the cpp files. This also means (I think) that I won't have to re-compile the c code every time I want to tweak the constants.

I'm used to scripting languages (python, js), so working with old C++ code is throwing me off a bit, and I'm sure parts of this question sound like I'm retarded, so, thanks for being patient with me.

These are just some weird dependencies, and I can't wrap my mind around unspooling it.

Ad

Answer

C++ literally inserts #include'd files into the code at compile time (technically before compile time - during the preprocessor run), so there is no way to change those values at runtime.

if you have the following

foo.h

const int value = 42;

and foo.cpp

#include "foo.h"
int foo(){ return value; }

When you compile foo.cpp, the preprocessor will substitute the exact contents of foo.h to replace #include "foo.h" in the cpp file and then the compiler will see

const int value = 42;
int foo(){ return value; }

and nothing else

The original source code for a c++ program is completely discarded once compilation is complete and is never used again.

You can see what the compiler sees using the -E flag to gcc which will make it output the pre-processed source.

Ad
source: stackoverflow.com
Ad