Allan
Allan

Reputation: 137

Using macros in C to change behavior in other C files

Is it possible to define a macro in a C file, and then change behavior of another C file using this definition?

For instance, suppose we have a file named b.c:

#include <stdio.h>
#define ABC

void function() {
    printf("b.c\n");
}

And another file named a.c:

#include <stdio.h>

int main() {
    #ifdef ABC
        printf("b.c defined this\n");
    #endif
    printf("a.c\n");
}

These files are compiled together. I want the definition of ABC in b.c to influence a.c.

I know I was supposed to be using a header file, but I don't want to do that. Is there another way to achieve this?

In my scenario, b.c is a sort of sub-application that will complement the behavior of a.c, and it should also be able to override behavior in there.

Is there an alternative to macros that can achieve this?

Upvotes: 0

Views: 771

Answers (4)

mouviciel
mouviciel

Reputation: 67889

It doesn't work the way you describe.

#define ABC only defines ABC within the scope of the b.c file, and does not impact other files (unless b.c is #included).

The only way to define ABC within the scope of a.c file without header files is to define ABC using the command line arguments of the compiler: gcc -D ABC ...

Upvotes: 1

ugoren
ugoren

Reputation: 16449

As others said, you can't do it.

Your options:
1. Don't use macros. Generally, it's good advice. There are some things that can't be done without macros, but normally you don't see them. You'll get better code without macros.
2. Define the macro in a header file, which is included by both C files.

Upvotes: 1

Serge
Serge

Reputation: 6095

No this is not possible this way. But you may instruct compiler to define a symbol using command line options

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182883

Use global variables or use callbacks. The "best" solution depends on precisely how much flexibility you need.

Upvotes: 2

Related Questions