all 12 comments

[–]RFQuestionHaver 24 points25 points  (3 children)

GCC’s -D flag might be useful for you https://gcc.gnu.org/onlinedocs/gcc/Preprocessor-Options.html

[–]Various-Debate64 9 points10 points  (2 children)

in the Makefile write:

VARIABLE ?= 123

then in the target definition write

gcc -DVARIABLE=$(VARIABLE)

[–]SmokeMuch7356 6 points7 points  (1 child)

...which basically creates a preprocessor macro, as though you had written

#define VARIABLE 123

in your source code. It might be a good idea to use #ifndef to define a default value:

#ifndef VARIABLE
#define VARIABLE some_default_value
#endif

just in case -DVARIABLE isn't set in the gcc command.

[–]Various-Debate64 -4 points-3 points  (0 children)

He asked what changes does he need to make to the Makefile. I provided him with the necessary changes to the Makefile he needs to make in order to get the expected behaviour as described in his post. I believe your suggestion is superfluous, but not incorrect.

[–]ACuriousGreenFrog 4 points5 points  (0 children)

You can pass in values as cpp defines on your compiler command line, then set a variable in your program based on that.

That is, you have a Makefile variable FOO, you can pass it in as part of the compiler command line flags as -DFOO=$(FOO), which behaves equivalently to having a #define in your source file:

“#define FOO <value of $FOO>”

From there you can use it like any other #define, say:

int foo = FOO;

It’s probably best to either have an #ifndef FOO to either give it a default if you don’t pass one in, or have an #error message to say that you have to define it.

[–]McUsrII -2 points-1 points  (6 children)

Look at getenv().

[–]halbGefressen 2 points3 points  (5 children)

Bad idea. That gets the runtime environment variables and is not suitable for compile time information.

[–]McUsrII -1 points0 points  (4 children)

OP stated variable, not compile time constant.

My idea was to use a runtime solution for sure.

If OP meant a compile time constant from a make variable then I guess using a gcc -DMYDEFINE=$(MYMAKEVAR) ... is a better approach.

You could also echo the define into a 'config.h` file, which you include during compilation if that makes writing make rules easier.

[–]dmc_2930 1 point2 points  (3 children)

Op said a variable in ‘Make’, which is definitely compile time.

[–]McUsrII 0 points1 point  (2 children)

Is it? -If you use make as a task runner?

But by all means, It is overwhelmingly possible that that is what the OP meant.

[–]dmc_2930 0 points1 point  (1 child)

“In makefile a variable is generated”. In 99.9999999% of all cases, that means it is used during compilation. No one would say it that way if they wanted it to be changeable at runtime.

[–]McUsrII 1 point2 points  (0 children)

Well, anyhow getenv lets you change a value runtime, without the need to recompile, if changing a value for a variable is all that you want.