Preferred order of declarations and #defines in a header file - c

I am programing in C language in Linux platform . I want to know should be the order of declarations and #defines in a header file.
For example if my header file includes following thing can anyone please suggest me what should the perfect order to arrange all these declarations, function like macros , exteren declarations, etc.
This can be really beneficial for arranging all these things in a header file properly in terms of readability and coding standards.
Below is the sample header file (I want to arrange the following in a proper order) :
#include <pthread.h> // Including Header files
#include <signal.h>
#define IMAGE_DIRECTORY "Abcdefgh..." // Providing #defines
#define FAILED_TO_RECOGNIZE "Xykbkksk..."
#define PROGRESS_FRAME_COLOR "#8e8ea1"
#define FRAME_BG_COLOR "#7c90ac"
#define PRINT_FUNCTION_NAME fprintf(stderr,
"CTRL IN FUNCTION : %s\n",__func__); // Macro like functions
typedef struct {
int userId; // Structure
char name[32], rollNo[32];
char class[16], section[16];
unsigned long Id;
}data_type;
int noOfUsersList=0, usersListCount=0; // Global variables

I haven't done this for years but when I was heavily developing for Unix, MS.DOS, OS/2, NetWare, and Windows simultaneously I developed this practice:
Language #includes
Operating system #includes
#includes from other subsystems, e.g. X11.
My own application #includes.
My own local #defines for this source file.
My own forward declarations for this file.
Maybe you can reverse (1) and (2) but I found this order to work the best across quite a number of compilers and operating systems.

Coding style is subjective, personally I use the rules and methods described below, but please note that are my own opinions and no absolute truths. Yet they are based on long experience and in some cases on widely-recognized coding standards (MISRA, CERT etc).
Rules:
C programming is done in "code modules", where every module consists of a .h file and a .c file.
#includes shall always be in the .h file and never in the .h file, since the .h file should be regarded as public. You want the person that is going to use your module to know what dependencies there are.
There is never a reason to use non-const global variables in C, so where to place non-const globals and externs isn't relevant to me.
.h files shouldn't contain any definitions. This is not only bad program design, it is also an excellent way to conjure numerous hard-to-solve linker errors.
In a .h file, the following items are allowed to appear, in the stated order:
Start of header guard. (#ifndef MYHEADER_H ...)
Library #includes.
Other #includes.
Impl.-specific compiler settings such as compiler options set with #pragmas.
Public numeric constants as #defines.
Public macros.
Public type definitions, including opaque types.
Declaration of public constants (declared as extern const).
Inline function definitions (rare special case, avoid if possible).
Function prototypes.
End of header guard. #endif
In a .c file, the following items are allowed to appear, in the stated order:
Include of its own corresponding .h file.
Private numeric constants in #defines.
Private macros.
Definition of opaque types, that were declared as incomplete type in the corresponding .h file.
Private type definitions.
Definition of public constants (declared as extern const in the .h file).
Definition of private constants (static const).
Definition of private variables at file scope (static).
Declaration of private functions (declared as static type func (type param);)
Definition of the public functions declared in the .h file.
Definition of private functions.

Macro definitions with #define are not declarations. The only requirement is that macros should be defined before their usage. They stay defined until end of compilation unit, or an explicit #undef (or a redefinition...).
My stylistic convention is to define statement-like macros as having a "function" like syntax, something like:
#define PRINT_FUNCTION_NAME() fprintf(stderr, \
"CTRL IN FUNCTION: %s #%s:%d\n", __func__, __FILE__, __LINE__)
Notice the empty formal macro argument (ie first ()) and the lack of terminating semicolon (because you will use it as a quasi-function call, e.g. PRINT_FUNCTION_NAME(); statement). Notice also use of __FILE__ and __LINE__ in a debug message.
Quite often, a statement-like macro is a do{ something } while(0) because this is a syntax which has a statement like look and can always be used as a statement (including as the then part of an if, or in else branch, etc...). An example from <ncurses.h> :
#define getsyx(y,x) do { if (newscr) { \
if (is_leaveok(newscr)) \
(y) = (x) = -1; \
else \
getyx(newscr,(y), (x)); \
} \
} while(0)

Related

How Header files and macros are related?

just a beginner question, what's going on with #ifndef SOME_HEADER_H understandable that it is a preprocessor directive for conditional compilation, if some header is already included (i might be wrong correct me?) move on , if it's not, include it, i read at some blog the letter sentence with these words instead, if it's defined move on else #define it, well i thought we can just include a header file not define a header file , how can a header file be defined, and what's the relation here ? and the second question, the file name was foo.h and when he try to check if it's defined he does #ifndef FOO_H #define FOO_H, ok how foo.h have been translated to FOO_H , does the c mechanism know that he's talking about that specific file or does he done something before-word? thank's for your time!
There is no such thing as translating foo.h as FOO_H, nor such thing as "defining that a .h has already been included". Using preprocessor variables is just the standard way C developers ensure that .h are not included twice.
In C preprocessor, you can use things such as #if, #else and #endif in order to make logic. You can also #define variables, to store information. You can also use the function defined(...) to check if a C-preprocessor variable is already defined. The #ifdef MY_VARIABLE directive is just a shorthand for #if defined(MY_VARIABLE), and #ifndef is just the opposite of that.
On the other hand, you don't want a .h to be included twice, there are several ways to do this, but the standard way is:
/* Check if my variable has already been declared */
#ifndef MY_aWeSoMe_VARIBLE
/* If we are in here, it mean that it is not */
/* So let's declare it */
#define MY_aWeSoMe_VARIBLE
/* You can write some more code here, like your .h stuff */
/* And of course, it's time to close the if */
#endif /* This closes the MY_aWeSoMe_VARIABLE ifndef */
The 1st time your complier will include the .h, MY_aWeSoMe_VARIABLE won't be defined yet, so preprocessor will get inside the if, define the variable, include all the .h's code. If your compiler comes to include the .h a 2nd or more time, the variable will already be defined, so the preprocessor won't get inside the if. Since all the .h's content is inside the if, it won't do anything.
Since naming a variable MY_aWeSoMe_VARIABLE is pretty stupid, people tend to name it like MY_FILE_NAME, or MY_FILE_NAME_H, but this is not mandatory, practices actually vary from one dev to another.
What you have here is a header guard:
File: some_header.h
#ifndef SOME_HEADER_H // if SOME_HEADER_H is not defined, enter the
// #ifndef ... #endif block
#define SOME_HEADER_H // and define SOME_HEADER_H
struct foo {
int x;
};
#endif
This protects the header from being included more than once in the same translation unit and thereby trying to define the same entities more than once. The macro SOME_HEADER_H will stay defined until the translation unit is done so no matter how many times this header is included in the translation unit (implicitly via other header files) its contents will only be parsed once for that translation unit.
You can now do this:
File: some_other_header.h
#ifndef SOME_OTHER_HEADER_H
#define SOME_OTHER_HEADER_H
#include "some_header.h" // this header uses some_header.h
struct bar {
struct foo x;
};
#endif
And a program can now include both header files without getting an error like redefinition of 'foo'.
File: main.cpp
#include "some_header.h"
#include "some_other_header.h"
int main() {}
A non-standard but quite popular alternative to the classic header guards shown above is #pragma once which does the same thing (if your preprocessor supports it):
File: some_header.h
#pragma once
// no need for a named macro or #endif
struct foo { ... };

Confusion between header file macro declaration and pre-processor macro declaration

I am new to C, so please help me with an answer before downvoting, it will help me a lot.
The definition of header file states that-
A header file consists of C function declaration and macro definitions to be shared between different files.
And the definition of C Preprocessor states that-
The C preprocessor is a macro preprocessor that transforms your program before it is compiled.All preprocessor directives begin with the # symbol.
My question is the macro declaration are done using # symbol in a program, does it depend on inclusion or exclusion of any header file, also how to find whether a particular file has a pre-defined macro declaration in it.
For example-
Say a file 'ani.h' has a macro declaration,
#define anii 2
So, once I include this file, I am allowed to use the CNAME i.e. aniidirectly?
It is easier if you look at this form the view of what the pre-processor actually does.
It reads a file and replaces text and then output a new file. The new file is sent to the compiler. The pre-proc knows nothing about C code, its just a text manipulation engine
#include xxxx
says, 'replace this line by the contents of that file'
#define FOO BAR
says, 'whenever you see FOO replace it by BAR
There are also some simple conditionals: #if etc
A macro is simply a FOO BAR replacement, usually FOO is small and BAR is large.
Although they can be used to do some nice metaprogramming tricks as well as conditional programming, macros most basic use is to make programmers lives easier via syntactic sugaring. Before compiling your code, the preprocessor module will substitute all the macros by the terms they represent, so everything you define must have been declared somewhere above the point where the macro is first used. So if you do:
#include <stdio.h>
#include <math.h>
#define MY_MACRO(x) for(int i=0; i<(x); ++i) printf("%d\n", func((x),i);
int func(int n, int m) {return pow(n, m);}
int main()
{
int a = 10;
MY_MACRO(a)
return 0;
}
The preprocessor will substitute all occurrences of MY_MACRO in your code by the loop that was defined after it. The code will then be sent to compilation. When the compiler reaches the line where the macro is used, it is necessary that printf and func are declared somewhere above this line, just as if you were writing the code without the macro. (Note that printf and pow are declared in the headers included before the definition and func is declared after the definition, but them three are declared before the first use of the macro.)
In what concerns to knowing which macros are declared inside some lib and which aren't, I believe the only way is to check the header files you are using or to read their documentation. But if you know that some specific macro may or may not be declared, you can test it using the code below:
#ifdef SOME_MACRO
printf("SOME_MACRO defined!\n");
#else
printf("SOME_MACRO not defined!\n");
#endif

variable redefinition, embedded c

I'm working on an embedded c project and am having issues with global variable redefinition.
I've split up the function declarations and definitions into a handful of .h and .c files. Many of these functions need access to global variables, which are defined in global_vars.h. Therefore, at the beginning of the header files, inside the #ifndef, #define section, "global_vars.h". If I don't, as you might imagine I get a bunch of undefined variable errors.
However, even though global_vars.h has the #ifndef _GLOBAL_VARS_H_ #define... #endif, I get redefinition errors for all the global variables. My guess is that when the linker tries link the various object files, it sees the redefinition due to the #include "global_vars.h" in all the "blah_blah.h" files. It was my understanding, though, that the #ifndef... takes care of this issue.
Is there something I'm overlooking?
Thanks in advance
The linker never sees anything in the global_vars.h file, ever, unless -- bad news! -- some of the globals are actually defined in that file. global_vars.h should hold only declarations of those global variables, never (well, almost never) their definitions.
In global_vars.h, you should have declarations like:
extern int some_global;
You are not allowed to have:
int some_global;
If you have definitions in global_vars.h then, yes, they'll be multiply defined at link time because each of the .c files that #includes global_vars.h will have its own definition of each defined variable.
All of the definitions of the extern globals must be in some .c file, for sure. Usually it doesn't matter which .c file. Often all of the global-variable definitions are in a file called (surprise!) global_vars.c.
So make sure there aren't any global-variable definitions in global_vars.h and you'll be in good shape.
Is not a good idea to define globals in an H file. Better if you do that in a C or C++ file and you include and H file in other modules with those globals as externals.
Like this>>>
My module c file
unsigned short int AGLOBAL = 10; // definer and initializer
void MyFunc(void)
{
AGLOBAL+=1; // no need to include anything here cause is defined above
// more .....
}
My H file globals.h
// this is to include only once
#ifndef MYH
#define MYH
extern unsigned short int AGLOBAL; // no value in here!
#endif
Other module c file
#include globals.h
char SomeOtherFunc(void)
{
AGLOBAL+=10; // ok cause its defined by globals.h
// do more....
}
So let me start with saying that extern keyword applies to C variables (data objects) and C functions. Basically extern keyword extends the visibility of the C variables and C functions. Probably that’s is the reason why it was named as extern.
Use of extern with C functions. By default, the declaration and definition of a C function have “extern” prepended with them. It means even though we don’t use extern with the declaration/definition of C functions, it is present there.
For example, when we write.
int foo(int arg1, char arg2);
There’s an extern present in the beginning which is hidden and the compiler treats it as below.
extern int foo(int arg1, char arg2);
Same is the case with the definition of a C function (Definition of a C function means writing the body of the function). Therefore whenever we define a C function, an extern is present there in the beginning of the function definition. Since the declaration can be done any number of times and definition can be done only once, we can notice that declaration of a function can be added in several C/H files or in a single C/H file several times. But we notice the actual definition of the function only once (i.e. in one file only). And as the extern extends the visibility to the whole program, the functions can be used (called) anywhere in any of the files of the whole program provided the declaration of the function is known. (By knowing the declaration of the function, C compiler knows that the definition of the function exists and it goes ahead to compile the program).
So that’s all about extern with C functions.
Declaration can be done any number of times but definition only once.
“extern” keyword is used to extend the visibility of variables/functions().
Since functions are visible through out the program by default. The use of extern is not needed in function declaration/definition. Its use is redundant.
When extern is used with a variable, it’s only declared not defined.
As an exception, when an extern variable is declared with initialization, it is taken as definition of the variable as well.

#include <> files in different files

If I have a several header files :lets say 1.h, 2.h, 3.h.
Let's say the all three of the header files have #include <stdlib.h> and one of the include files in them.
When I have to use all 3 header files in a C file main.c,
it will have 3 copies of #include <stdlib.h> after the preprocessor.
How does the compiler handle this kind of conflict?
Is this an error or does this create any overhead?
If there are no header guards, what will happen?
Most C headers include are wrapped as follows:
#ifndef FOO_H
#define FOO_H
/* Header contents here */
#endif
The first time the preprocessor scans this, it will include the contents of the header because FOO_H is undefined; however, it also defines FOO_H preventing the header contents from being added a second time.
There is a small performance impact of having a header included multiple times: the preprocessor has to go to disk and read the header each time. This can be mitigated by adding guards in your C file to include:
#ifndef FOO_H
#include <foo.h>
#endif
This stuff is discussed in great detail in Large-Scale C++ Software Design (an excellent book).
This is usually solved with preprocessor statements:
#ifndef __STDLIB_H
#include <stdlib.h>
#define __STDLIB_H
#endif
Although I never saw it for common header files like stdlib.h, so it might just be necessary for your own header files.
The preprocessor will include all three copies, but header guards will prevent all but the first copy from being parsed.
Header guards will tell the preprocessor to convert subsequent copies of that header file to effectively nothing.
Response to edit:
Standard library headers will have the header guards. It would be very unusual and incorrect for them to not have the guards.
Similarly, it is your responsibility to use header guards on your own headers.
If header guards are missing, hypothetically, you will get a variety of errors relating to duplicate definitions.
Another point: You can redeclare a function (or extern variable) a bazillion times and the compiler will accept it:
int printf(const char*, ...);
int printf(const char*, ...);
is perfectly legal and has a small compilation overhead but no runtime overhead.
That's what happens when an unguarded include file is included more than once.
Note that it is not true for everything in an include file. You can't redeclare an enum, for example.
This is done by one of the two popular techniques, both of which are under stdlib's responsibility.
One is defining a unique constant and checking for it, to #ifdef out all the contents of the file if it is already defined.
Another is microsoft-specific #pragma once, that has an advantage of not having to even read the from the hard drive if it was already included (by remembering the exact path)
You must also do the same in all header files you produce. Or, headers that include yours will have a problem.
As far a I know regular include simply throws in the contents of another file. The standard library stdlib.h urely utilizes the code guards: http://en.wikipedia.org/wiki/Include_guard, so you end up including only one copy. However, you can break it (do try it!) if you do: #include A, #undef A_GUARD, #include A again.
Now ... why do you include a .h inside another .h? This can be ok, at least in C++, but it is best avoided. You can use forward declarations for that: http://en.wikipedia.org/wiki/Forward_declaration
Using those works for as long as your code does not need to know the size of an imported structure right in the header. You might want to turn some function arguments by value into the ones by reference / pointer to solve this issue.
Also, always utilize the include guards or #pragma once for your own header files!
As others have said, for standard library headers, the system must ensure that the effect of a header being included more than once is the same as the header being included once (they must be idempotent). An exception to that rule is assert.h, the effect of which can change depending upon whether NDEBUG is defined or not. To quote the C standard:
Standard headers may be included in any order; each may be included more than once in
a given scope, with no effect different from being included only once, except that the
effect of including <assert.h> depends on the definition of NDEBUG.
How this is done depends upon the compiler/library. A compiler system may know the names of all the standard headers, and thus not process them a second time (except assert.h as mentioned above). Or, a standard header may include compiler-specific magic (mostly #pragma statements), or "include guards".
But the effect of including any other header more than once need not be same, and then it is up to the header-writer to make sure there is no conflict.
For example, given a header:
int a;
including it twice will result in two definitions of a. This is a Bad Thing.
The easiest way to avoid conflict like this is to use include guards as defined above:
#ifndef H_HEADER_NAME_
#define H_HEADER_NAME_
/* header contents */
#endif
This works for all the compilers, and doesn't rely of compiler-specific #pragmas. (Even with the above, it is a bad idea to define variables in a header file.)
Of course, in your code, you should ensure that the macro name for include guard satisfies this:
It doesn't start with E followed by an uppercase character,
It doesn't start with PRI followed by a lowercase character or X,
It doesn't start with LC_ followed by an uppercase character,
It doesn't start with SIG/SIG_ followed by an uppercase character,
..etc. (That is why I prefer the form H_NAME_.)
As a perverse example, if you want your users guessing about certain buffer sizes, you can have a header like this (warning: don't do this, it's supposed to be a joke).
#ifndef SZ
#define SZ 1024
#else
#if SZ == 1024
#undef SZ
#define SZ 128
#else
#error "You can include me no more than two times!"
#endif
#endif

How to correctly use the extern keyword in C

My question is about when a function should be referenced with the extern keyword in C.
I am failing to see when this should be used in practice. As I am writing a program all of the functions that I use are made available through the header files I have included. So why would it be useful to extern to get access to something that was not exposed in the header file?
I could be thinking about how extern works incorrectly, and if so please correct me.
Also.. Should you extern something when it is the default declaration without the keyword in a header file?
extern changes the linkage. With the keyword, the function / variable is assumed to be available somewhere else and the resolving is deferred to the linker.
There's a difference between extern on functions and on variables.
For variables it doesn't instantiate the variable itself, i.e. doesn't allocate any memory. This needs to be done somewhere else. Thus it's important if you want to import the variable from somewhere else.
For functions, this only tells the compiler that linkage is extern. As this is the default (you use the keyword static to indicate that a function is not bound using extern linkage) you don't need to use it explicitly.
extern tells the compiler that this data is defined somewhere and will be connected with the linker.
With the help of the responses here and talking to a few friends here is the practical example of a use of extern.
Example 1 - to show a pitfall:
stdio.h:
int errno;
myCFile1.c:
#include <stdio.h>
// Code using errno...
myCFile2.c:
#include <stdio.h>
// Code using errno...
If myCFile1.o and myCFile2.o are linked, each of the c files have separate copies of errno. This is a problem as the same errno is supposed to be available in all linked files.
Example 2 - The fix.
stdio.h:
extern int errno;
stdio.c:
int errno;
myCFile1.c:
#include <stdio.h>
// Code using errno...
myCFile2.c:
#include <stdio.h>
// Code using errno...
Now if both myCFile1.o and MyCFile2.o are linked by the linker they will both point to the same errno. Thus, solving the implementation with extern.
It has already been stated that the extern keyword is redundant for functions.
As for variables shared across compilation units, you should declare them in a header file with the extern keyword, then define them in a single source file, without the extern keyword. The single source file should be the one sharing the header file's name, for best practice.
Many years later, I discover this question. After reading every answer and comment, I thought I could clarify a few details... This could be useful for people who get here through Google search.
The question is specifically about using extern functions, so I will ignore the use of extern with global variables.
Let's define 3 function prototypes:
// --------------------------------------
// Filename: "my_project.H"
extern int function_1(void);
static int function_2(void);
int function_3(void);
The header file can be used by the main source code as follows:
// --------------------------------------
// Filename: "my_project.C"
#include "my_project.H"
void main(void) {
int v1 = function_1();
int v2 = function_2();
int v3 = function_3();
}
int function_2(void) return 1234;
In order to compile and link, we must define function_2 in the same source code file where we call that function. The two other functions could be defined in different source code *.C or they may be located in any binary file (*.OBJ, *.LIB, *.DLL), for which we may not have the source code.
Let's include again the header my_project.H in a different *.C file to understand better the difference. In the same project, we add the following file:
// --------------------------------------
// Filename: "my_big_project_splitted.C"
#include "my_project.H"
void old_main_test(void){
int v1 = function_1();
int v2 = function_2();
int v3 = function_3();
}
int function_2(void) return 5678;
int function_1(void) return 12;
int function_3(void) return 34;
Important features to notice:
When a function is defined as static in a header file, the compiler/linker must find an instance of a function with that name in each module which uses that include file.
A function which is part of the C library can be replaced in only one module by redefining a prototype with static only in that module. For example, replace any call to malloc and free to add memory leak detection feature.
The specifier extern is not really needed for functions. When static is not found, a function is always assumed to be extern.
However, extern is not the default for variables. Normally, any header file that defines variables to be visible across many modules needs to use extern. The only exception would be if a header file is guaranteed to be included from one and only one module.
Many project managers would then require that such variable be placed at the beginning of the module, not inside any header file. Some large projects, such as the video game emulator "Mame" even require that such variables appears only above the first function using them.
In C, extern is implied for function prototypes, as a prototype declares a function which is defined somewhere else. In other words, a function prototype has external linkage by default; using extern is fine, but is redundant.
(If static linkage is required, the function must be declared as static both in its prototype and function header, and these should normally both be in the same .c file).
A very good article that I came about the extern keyword, along with the examples: http://www.geeksforgeeks.org/understanding-extern-keyword-in-c/
Though I do not agree that using extern in function declarations is redundant. This is supposed to be a compiler setting. So I recommend using the extern in the function declarations when it is needed.
If each file in your program is first compiled to an object file, then the object files are linked together, you need extern. It tells the compiler "This function exists, but the code for it is somewhere else. Don't panic."
All declarations of functions and variables in header files should be extern.
Exceptions to this rule are inline functions defined in the header and variables which - although defined in the header - will have to be local to the translation unit (the source file the header gets included into): these should be static.
In source files, extern shouldn't be used for functions and variables defined in the file. Just prefix local definitions with static and do nothing for shared definitions - they'll be external symbols by default.
The only reason to use extern at all in a source file is to declare functions and variables which are defined in other source files and for which no header file is provided.
Declaring function prototypes extern is actually unnecessary. Some people dislike it because it will just waste space and function declarations already have a tendency to overflow line limits. Others like it because this way, functions and variables can be treated the same way.
Functions actually defined in other source files should only be declared in headers. In this case, you should use extern when declaring the prototype in a header.
Most of the time, your functions will be one of the following (more like a best practice):
static (normal functions that aren't
visible outside that .c file)
static inline (inlines from .c or .h
files)
extern (declaration in headers of the
next kind (see below))
[no keyword whatsoever] (normal
functions meant to be accessed using
extern declarations)
When you have that function defined on a different dll or lib, so that the compiler defers to the linker to find it. Typical case is when you are calling functions from the OS API.

Resources