user1295872
user1295872

Reputation: 509

Can you extern a #define variable in another file?

For example abc.c contains a variable

#define NAME "supreeth"

Can extern the variable NAME in def.c?

Upvotes: 18

Views: 45793

Answers (3)

MOHAMED
MOHAMED

Reputation: 43518

You can not use extern with macro. but if you want your macro seen by many C files

put your macro definition

#define NAME "supreeth"

in a header file like def.h

then include your def.h in your C code and then you can use your macro in your C file in all other C file if you include def.h

Upvotes: 23

Sudhee
Sudhee

Reputation: 714

If you have #define NAME "supreeth" in abc.c, you can surely have a extern variable by same name in another file def.c, this is as far as the compiler is concerned. If you are implying some kind of dependency between these two, that dependency/linkage will not happen. Obviously it is confusing and a bad idea to do something like this.

Upvotes: 4

unwind
unwind

Reputation: 399793

In your code NAME is not a variable. It's a pre-processor symbol, which means the text NAME will be replaced everywhere in the input with the string "supreeth". This happens per-file, so it doesn't make sense to talk about it being "external".

If a particular C file is compiled without that #define, any use of NAME will remain as-is.

Upvotes: 16

Related Questions