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.

Advertisements

One Response to “Is it acceptable to declare/define a variable in a C header?”

  1. gergap Says:

    I totally agree and every developer should know that. But I see this mistakes again and again. Mostly by this point & click developers that don’t even know how a build process works. Every developer should have written at least one Makefile by himself, know about preprocessor, compiler and linker, and so understand the difference between declaration and definition and so understand the problem with multiple definitions. GUIs are evil 🙂

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: