Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you extern a #define variable in another file?

Tags:

c

extern

global

For example abc.c contains a variable

#define NAME "supreeth"

Can extern the variable NAME in def.c?

like image 551
user1295872 Avatar asked Apr 29 '13 13:04

user1295872


People also ask

Can you extern a function in C?

The extern keyword in C and C++ extends the visibility of variables and functions across multiple source files. In the case of functions, the extern keyword is used implicitly. But with variables, you have to use the keyword explicitly.

Can #define extern in C?

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.

How do you use extern with examples?

“extern” keyword is used to extend the visibility of function or variable. By default the functions are visible throughout the program, there is no need to declare or define extern functions. It just increase the redundancy. Variables with “extern” keyword are only declared not defined.

What is an extern variable in C?

Extern is a keyword in C programming language which is used to declare a global variable that is a variable without any memory assigned to it. It is used to declare variables and functions in header files. Extern can be used access variables across C files.


2 Answers

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

like image 101
MOHAMED Avatar answered Sep 19 '22 05:09

MOHAMED


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.

like image 33
unwind Avatar answered Sep 20 '22 05:09

unwind