Jonas
Jonas

Reputation: 1069

Redefine macro from outside its defining file

"redefining" a macro, that has already been defined in another header file, to control the behavior of, lets say, the functions using it.

An example would make things more clear.

/* foo.h */
#ifndef FOO_H
#define FOO_H

#ifndef MAX_LEN
    #define MAX_LEN 256
#endif

void foo();

#endif

the function foo() just prints the value of the macro defined in the header

/* foo.c */
#include <stdio.h>
#include "foo.h"

void foo()
{
    printf("%d", MAX_LEN);
}

When I run the following code, I will get the output 256

/* main.c */
#include "foo.h"

int main()
{
    foo();

    return 0;
}

Now, what I want is to change MAX_LEN from inside of main.c so that I would get a different result

/* main.c */
#define MAX_LEN 16
#include "foo.h"

int main()
{
    foo();

    return 0;
}

The output is still 256 and not 16? How can that be?

Also read

Upvotes: 1

Views: 816

Answers (2)

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

The problem is that the foo.c file is preprocessed before the files are linked together. This means that it's compiled with MAX_LEN set to 256 and when main.o is linked to foo.o it was already compiled like this

void foo()
{
    printf("%d", 256);
}

This is the result of (without #include <stdio.h>)

gcc -E foo.c   

# 1 "foo.c"
# 1 "<interno>"
# 1 "<línea-de-orden>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<línea-de-orden>" 2
# 1 "foo.c"

# 1 "foo.h" 1
# 9 "foo.h"
void foo();
# 3 "foo.c" 2

void foo()
{
    printf("%d", 256);
}

So when it's compiled it's compiled as it is because you are not including the "foo.c" file in "main.c".

Upvotes: 1

D.Shawley
D.Shawley

Reputation: 59563

The definition of MAX_LEN that matters is the one that foo.c sees when it is compiled. It doesn't matter how it is defined in main.c. The only way to modify what is printed from within foo is to define MAX_LEN when you compile foo.c. Usually something like gcc -DMAX_LEN=16 -c foo.c will do the job.

In other words, you cannot affect the foo.c compilation unit from within main.c.

Upvotes: 2

Related Questions