How to set a compile variable?

I want to set a variable so I can compile C code depending on if this variable is defined or not.

The way that you can pass "variables" to the compilation process in C is "preprocessor defines".

The easiest way to deal with changing a define is just to do it yourself at the top of a file...editing by hand, when you want to define something or not.

#define VAR_NAME

#ifdef VAR_NAME
    int code_done_one_way(void) {...}
#else
    int code_done_another_way(void) {...}
#endif

But if you don't want to edit a file to set the variable...but have it "come from the environment" somehow, then you have to find a way to pass the variable definition to the C compiler.

On the command line for a C compiler, you define them with -D by saying -DVAR_NAME=VALUE ... there also exists the concept of "just being defined, but not having a value. That is done with -DVAR_NAME

In the make process, the make.r step will go through the extensions, and run code setting up what defines are active. This means you can do things like query OS environment variables.

Notice here the TCC extension looks to see if an environment variable is set to decide whether to pass -DNEEDS_FAKE_STRTOLD in the "cflags" command line flags to the C compiler:

1 Like

Right that is about what I wanted to know.
So it should also be possible to set this inside a config file using set-env!
Super! Thanks!
(It is often harder to find the right example :wink: )

Tested set-env and while it would work for the purpose I have in mind I noticed something.
Set-env does not set the environment variable. When using set-env "THE_SET_VARIABLE" "Hi", exiting r3 and returning to the shell, echo $THE_SET_VARIABLE returns an empty line.

Each executing process typically gets a copy of the environment, and changes are lost.

I mentioned this before regarding why it's important in the shell to say export THE_SET_VARIABLE="hi" and not just set THE_SET_VARIABLE="hi"...because the SET command will only be applicable while running SET.

Anyway, it doesn't really make sense for the makefile generation process to be setting environment variables. You set CFLAGS from environment variables...it's a way to pass information from your shell and environment to make.r in lieu of having a way of doing it in the configuration process itself.

1 Like

So if I would really want it, I'd have to create a function export-env. :wink:

A user program is run by shells as a "child process", and does not have the power to make changes to its calling environment.

This is a unique power given to a few things, like the shell itself.

I know, it should be able to edit some .bashrc file. I am not going to even try, don't worry!