jumbo_bigO
jumbo_bigO

Reputation: 33

Dynamically change define macros in c

I'm not sure if my question makes sense or not but I'm trying to write a program which changes the value of a define macro if a specific flag is used with the program.

By default the define value is set to 256, and if the user enters ./program_name value I would like the value to be the new define macro. Here is the c code below.

macro defined at the top of the file:

#define NUMBER_OF_VALUES 256

inside the main function:

if (strcmp(argv[1], "256")) {
    #ifdef NUMBER_OF_VALUES
    #undef NUMBER_OF_VALUES
    #define NUMBER_OF_VALUES 128
    #endif
}
else if (strcmp(argv[1], "128")) {
    // do nothing
}

How this code works, or how I find it to work is that if the value input is 256 it does nothing, and while the value is 128 tries to undefine the define macro and define it again with the new value i.e. 128.

However, this does not work, and when the value of 128 is used it still performs by default with the value of 256.

Upvotes: 3

Views: 2071

Answers (3)

mkingmking
mkingmking

Reputation: 51

The compiler first converts the .c to the .o form, then converts it to the .exe form. (for windows) In the transition from .c to .o, macro codes are converted to numeric values. other variables are evaluated in step 2. Therefore, it is not possible to change macro values at runtime.

Upvotes: 1

Gus
Gus

Reputation: 145

Macros are processed before compilation let alone run-time. So, it's impossible to define a macro on the fly.

The closest you could get is to create a global variable and modify it through a pointer.

However, you would be best off by just using a local variable with a default value.

int NUMBER_OF_VALUES = 256;
if (strcmp(argv[1], "128")) {
   NUMBER_OF_VALUES = 128
}

If your intention is to use a NUMBER_OF_VALUES to allocate a stack array of a specific size at run time, that simply isn't possible. You'll need to call malloc.

Upvotes: 3

Devolus
Devolus

Reputation: 22094

You can not change a macro at runtime, because they are evaluated by the preprocessor before the compiler even sees them, and replaced with their respective text representation.

This is done before the actual compiler starts to compile the code.

You can even see this for yourself, when you use the -E switch with gcc. For other compilers they may offer a similar option.

Upvotes: 0

Related Questions