Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding double inclusion: Preprocessor directive vs. makefiles

I'm working on moving from frankenstein and one-file thousands-of-lines programs to well structured and organized, multi-file programs. Right now what seems to be natural (naively) is to make a love-triangle of header inclusions for three of my files:
file_1 includes file_2, file_4
file_2 includes file_3, file_4
file_3 includes file_1 .... etc etc
These files have variables, methods, structs, etc that I need between other files.

And of course I'm getting double inclusion errors.

My question: should I avoid these problems by using preprocessor directives in headers (e.g. including structs, methods, etc. entirely in the header), or should I be compiling using a makefile (which I hear can also be used to resolve this problem---but I've never made one)?

like image 989
DilithiumMatrix Avatar asked Feb 15 '11 07:02

DilithiumMatrix


2 Answers

You should always use include guards so that you can include your common header files whenever needed. This is really independent of Makefile or whatever build tool you choose to use.

You should also try and avoid circular dependencies if possible, otherwise you will need to use forward declarations to resolve them.

like image 69
sjr Avatar answered Sep 28 '22 15:09

sjr


Preprocessor directives and headers containing declaration and shared structures etc is the way to go. Makefiles just helps to compile sources and to link object files to external libraries to form the final binary, it won't help to resolve the multiple-inclusion issue. In a nutshell, declare the following in a header file:

  • structs
  • shared variable as extern (and define it in one of the .c files)
  • method declaration (and define the methods in one of the .c files)

protect them with #IFNDEF and #ENDIF, then include the header file into the various .c files...

like image 44
whjou Avatar answered Sep 28 '22 15:09

whjou