DGerman
DGerman

Reputation: 62

Should I avoid using guard macros?

I am well aware of the reason cited often regarding the use of the guard macros

#ifndef special_func_lib
#define special_func_lib
...
#endif

I appreciate that this is important to permit multiple includes due to "nesting" espically when creating library utility function sets in a single source file.

When creating a header file for a high level set of functions (i.e. not expected to be included in another include) I want the preprocessor to produce an error if the include of the same header file occurred more than once and not just ignore it.

For example:

/* +++++++ file main.c +++++ */

#include main.h
int main () {
int pb2au1= resolve( POTION, 1);
int pb2au2= resolve( POTION, 2);
exit pb2au1 + pbau2;
}

/* +++ file main.h +++ */

#include <stdio.h>
#define POTION 886688

/* +++ file resolve.c +++ */

#include resolve.h
int resolve ( int mass, int heat )
{ return  mass + heat }

/* +++ file resolve.h +++ */

int resolve ( int ir1, int ir2 ); /* protype */

I don't want either main.h or resolve.h to be included more than once in a single source file.

What am I over looking?

Upvotes: 0

Views: 85

Answers (2)

When creating a header file for a high level set of functions (i.e. not expected to be included in another include) I want the preprocessor to produce an error

You could code

/*in file header.h*/
#ifdef HEADER_H_INCLUDED
#error header.h already included
#endif
#define HEADER_H_INCLUDED
/// other declarations should go here

Upvotes: 2

dbush
dbush

Reputation: 224512

What you have in your header files are not declarations of the functions but definitions. These definitions conflict the the definitions in the .c files.

Declarations for the functions would look like this:

int pb2au(int mass1, int heat); 

int resolve ( int ir1, int ir2 );

With this change, your code will compile and you won't have a problem if a header is included more than once. Still, it's a good idea to add header guards anyway.

Upvotes: 1

Related Questions