Is it acceptable to declare/define a variable in a C header?

A global variable that must be accessed from more than one file can and should be declared in a header file. In addition, such a variable must be defined in one source file. Variables should not be defined in header files, because the header file can be included in multiple source files, which would cause multiple definitions of the variable. The ANSI C standard will allow multiple external definitions, provided that there is only one initialization. But because there’s really no advantage to using this feature, it’s probably best to avoid it and maintain a higher level of portability. “Global” variables that do not have to be accessed from more than one file should be declared static and should not appear in a header file.  

Showing Answers 1 - 1 of 1 Answers

A variable can be declare/define in a C Header without any kind of compilational/ logical errors. But it is against the coding specifications and it is not normally practiced. If proper Multiple inclusion protection macro is used, then there will be no problem even the header is included in many .c files. In this case, no problem with multiple instances of the same variable due to header file multi inclusion in many .c/.h files

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions