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 { ... };
I am doing my first "big/medium" project for a school work and I need to divide my code into some other c files. My doubt is if it is better have many files/header files with just a few little code, or have less files/header files and a little more code/functions into them?
Thank you!
p.s. I am a newbie programmer, so be patient and try to make the explanation easy to understand.
My experience is that having code grouped into source/headers according to functionality increases ability to understand, test, maintain and reuse it.
How much code goes into each file will really depend on how complex the encapsulated functionality is. For example, I have a source file containing functions to create and append to WAV files. They are relatively small, and because they are cohesive, I can use them in whatever project I have that needs to create WAV files without bringing in a lot of other baggage. Other files may be large (or very large) but if the functionality is cohesive, I get the same benefits.
One thing that tripped me up when I started doing this was “multiple inclusions” caused by including the same header in a project multiple times without “protecting” it. Since you say you are a newbie, I’ll add a quick sample of what you can do to prevent it.
/**
#file my_header.h
*/
ifndef MY_HEADER_H // <- Prevents multiple inclusions
#define MY_HEADER_H // <- ...
#ifdef __cplusplus // <- Allows this to be called from c++
extern "C" { // <- See "name mangling for more info.
#endif // <- ...
/**************************/
// your stuff goes here
struct my_struct
{
// ...
};
// function prototypes, etc.
/**************************/
#ifdef __cplusplus
}
#endif
#endif // MY_HEADER_H
I am struggling to understand if I can prevent exposing certain function calls from within a DLL that I am building. The function calls I want to hide are calls that are exposed by sqlite3.dll which I am building into another DLL of my own making. sqlite3.dll exposes 5 functions, one of which looks like this in the header:
SQLITE_API int SQLITE_STDCALL sqlite3_close(sqlite3*);
The macros at play here are defined earlier as:
/*
** Provide the ability to override linkage features of the interface.
*/
#ifndef SQLITE_EXTERN
# define SQLITE_EXTERN extern
#endif
#ifndef SQLITE_API
# define SQLITE_API
#endif
#ifndef SQLITE_CDECL
# define SQLITE_CDECL
#endif
#ifndef SQLITE_STDCALL
# define SQLITE_STDCALL
#endif
Now, I am building sqlite3.dll into my application by linking against sqlite3.lib and including sqlite3.h (the source of the prior code snippets).
I realize I may be able to play with those macros to achieve what I want.
I expose the functions in my own dll with:
/* module entry point */
int __declspec(dllexport) __stdcall load_properties(CAObjHandle context);
When I look at the functions available in the output of my build, I get my functions+5 functions from the sqlite library. All of the functions in sqlite that are exposed have the declaration structure similar to what I showed for close() above.
Is there a way I can hide the sqlite functions? Is it the .lib file that is causing the issue? That file was auto-generated so I am not sure what is in there.
I discovered the answer. The sqlite3.dll was incorrectly specified as a source of exports to the compiler. Removing the directive to export functions from sqlite3.dll corrected the issue.
My objective is to instantiate an array in one C-file and have it initialised in different files only through declarative code, i.e., if the following would work, that'd be awesome:
// File1.c
int myArray[2];
// FileA.c
myArray[0] = 123;
// FileB.c
myArray[1] = 345;
The key here is that the code in FileA and FileB is not executed, but what I'd like to see is the compiler picking up these statements to initialise myArray.
What I'm really trying to accomplish here is some form of compilation-based service registration. I.e., in my real code, the array would hold pointers to functions, and my "main" (in File1.c) would not know which specific functions are compiled into the image. Via a different makefile, I would compile different combinations of my files (FileA, FileB, FileC...) and have the functions they implement available to my main via pointers.
Does anyone have an idea how to accomplish this?
You cannot initialize an array piecemeal across several files. You're only allowed one initializer in one file. So, that idea isn't going to work directly.
How can you make it work? You have pointers to functions; I assume they all have the same signature, which can be int function(int arg) for the purposes of this discussion (the details don't matter). It will be defined in a header, and that header will be needed by File1.c.
typedef int (*Function)(int arg);
Each service provider file will have an associated header, FileA.c has a header FileA.h, and so on.
The code that initializes the array could be in File1.c or in a separate file. Wherever it is, it will have to be cognizant of which modules (services) are to be linked:
#include "configuration.h"
#include "FileA.h"
#include "FileB.h"
#include "FileC.h"
Function services[] =
{
#ifdef INCLUDE_SERVICE_A
A_service_function,
#endif
#ifdef INCLUDE_SERVICE_B
B_service_function,
#endif
#ifdef INCLUDE_SERVICE_C
C_service_function,
#endif
};
size_t num_services = sizeof(services) / sizeof(services[0]);
This scheme has the benefit that there is no wasted space in the array. It also won't compile if none of the three services are requested. The build system will ensure that configuration.h includes the correct defines. The per-service headers declare the service functions.
So that gives an outline of a workable scheme.
Is it necessary to #include some file, if inside a header (*.h), types defined in this file are used?
For instance, if I use GLib and wish to use the gchar basic type in a structure defined in my header, is it necessary to do a #include <glib.h>, knowing that I already have it in my *.c file?
If yes do I also have to put it between the #ifndef and #define or after the #define?
NASA's Goddard Space Flight Center (GSFC) rules for headers in C state that it must be possible to include a header in a source file as the only header, and that code using the facilities provided by that header will then compile.
This means that the header must be self-contained, idempotent and minimal:
self-contained — all necessary types are defined by including relevant headers if need be.
idempotent — compilations don't break even if it is included multiple times.
minimal — it doesn't define anything that is not needed by code that uses the header to access the facilities defined by the header.
The benefit of this rule is that if someone needs to use the header, they do not have to struggle to work out which other headers must also be included — they know that the header provides everything necessary.
The possible downside is that some headers might be included many times; that is why the multiple inclusion header guards are crucial (and why compilers try to avoid reincluding headers whenever possible).
Implementation
This rule means that if the header uses a type — such as 'FILE *' or 'size_t' - then it must ensure that the appropriate other header (<stdio.h> or <stddef.h> for example) should be included. A corollary, often forgotten, is that the header should not include any other header that is not needed by the user of the package in order to use the package. The header should be minimal, in other words.
Further, the GSFC rules provide a simple technique to ensure that this is what happens:
In the source file that defines the functionality, the header must be the first header listed.
Hence, suppose we have a Magic Sort.
magicsort.h
#ifndef MAGICSORT_H_INCLUDED
#define MAGICSORT_H_INCLUDED
#include <stddef.h>
typedef int (*Comparator)(const void *, const void *);
extern void magicsort(void *array, size_t number, size_t size, Comparator cmp);
#endif /* MAGICSORT_H_INCLUDED */
magicsort.c
#include <magicsort.h>
void magicsort(void *array, size_t number, size_t size, Comparator cmp)
{
...body of sort...
}
Note that the header must include some standard header that defines size_t; the smallest standard header that does so is <stddef.h>, though several others also do so (<stdio.h>, <stdlib.h>, <string.h>, possibly a few others).
Also, as mentioned before, if the implementation file needs some other headers, so be it, and it is entirely normal for some extra headers to be necessary. But the implementation file ('magicsort.c') should include them itself, and not rely on its header to include them. The header should only include what users of the software need; not what the implementers need.
Configuration headers
If your code uses a configuration header (GNU Autoconf and the generated 'config.h', for example), you may need to use this in 'magicsort.c':
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif /* HAVE_CONFIG_H */
#include "magicsort.h"
...
This is the only time I know of that the module's private header is not the very first header in the implementation file. However, the conditional inclusion of 'config.h' should probably be in 'magicsort.h' itself.
Update 2011-05-01
The URL linked above is no longer functional (404). You can find the C++ standard (582-2003-004) at EverySpec.com; the C standard (582-2000-005) seems to be missing in action.
The guidelines from the C standard were:
§2.1 UNITS
(1) Code shall be structured as units, or as stand-alone header files.
(2) A unit shall consist of a single header file (.h) and one or more body (.c) files. Collectively the header and body files are referred to as the source files.
(3) A unit header file shall contain all pertinent information required by a client unit. A unit’s
client needs to access only the header file in order to use the unit.
(4) The unit header file shall contain #include statements for all other headers required by the unit header. This lets clients use a unit by including a single header file.
(5) The unit body file shall contain an #include statement for the unit header, before all other #include statements. This lets the compiler verify that all required #include statements are in
the header file.
(6) A body file shall contain only functions associated with one unit. One body file may not
provide implementations for functions declared in different headers.
(7) All client units that use any part of a given unit U shall include the header file for unit U; this
ensures that there is only one place where the entities in unit U are defined. Client units may
call only the functions defined in the unit header; they may not call functions defined in the
body but not declared in the header. Client units may not access variables declared in the body
but not in the header.
A component contains one or more units. For example, a math library is a component that contains
multiple units such as vector, matrix, and quaternion.
Stand-alone header files do not have associated bodies; for example, a common types header does
not declare functions, so it needs no body.
Some reasons for having multiple body files for a unit:
Part of the body code is hardware or operating system dependent, but the rest is common.
The files are too large.
The unit is a common utility package, and some projects will only use a few of the
functions. Putting each function in a separate file allows the linker to exclude the ones not
used from the final image.
§2.1.1 Header include rationale
This standard requires a unit’s header to contain #include statements for all other headers required
by the unit header. Placing #include for the unit header first in the unit body allows the compiler to
verify that the header contains all required #include statements.
An alternate design, not permitted by this standard, allows no #include statements in headers; all
#includes are done in the body files. Unit header files then must contain #ifdef statements that check
that the required headers are included in the proper order.
One advantage of the alternate design is that the #include list in the body file is exactly the
dependency list needed in a makefile, and this list is checked by the compiler. With the standard
design, a tool must be used to generate the dependency list. However, all of the branch
recommended development environments provide such a tool.
A major disadvantage of the alternate design is that if a unit’s required header list changes, each file
that uses that unit must be edited to update the #include statement list. Also, the required header list
for a compiler library unit may be different on different targets.
Another disadvantage of the alternate design is that compiler library header files, and other third party
files, must be modified to add the required #ifdef statements.
A different common practice is to include all system header files before any project header files, in
body files. This standard does not follow this practice, because some project header files may
depend on system header files, either because they use the definitions in the system header, or
because they want to override a system definition. Such project header files should contain #include
statements for the system headers; if the body includes them first, the compiler does not check this.
GSFC Standard available via Internet Archive 2012-12-10
Information courtesy Eric S. Bullington:
The referenced NASA C coding standard can be accessed and downloaded via the Internet archive:
http://web.archive.org/web/20090412090730/http://software.gsfc.nasa.gov/assetsbytype.cfm?TypeAsset=Standard
Sequencing
The question also asks:
If yes, do I also have to put it (the #include lines) between the #ifndef and #define or after the #define.
The answer shows the correct mechanism — the nested includes, etc, should be after the #define (and the #define should be the second non-comment line in the header) — but it doesn't explain why that's correct.
Consider what happens if you place the #include between the #ifndef and #define. Suppose the other header itself includes various headers, perhaps even #include "magicsort.h" indirectly. If the second inclusion of magicsort.h occurs before #define MAGICSORT_H_INCLUDED, then the header will be included a second time before the types it defines are defined. So, in C89 and C99, any typedef type name will be erroneously redefined (C2011 allows them to be redefined to the same type), and you will get the overhead of processing the file multiple times, defeating the purpose of the header guard in the first place. This is also why the #define is the second line and is not written just before the #endif. The formula given is reliable:
#ifndef HEADERGUARDMACRO
#define HEADERGUARDMACRO
...original content of header — other #include lines, etc...
#endif /* HEADERGUARDMACRO */
A good practice is to only put #includes in an include file if the include file needs them. If the definitions in a given include file are only used in the .c file then include it only in the .c file.
In your case, i would include it in the include file between the #ifdef/#endif.
This will minimize dependencies so that files that don't need a given include won't have to be recompiled if the include file changes.
Usually, library developers protect their includes from multiple including with the #ifndef /#define / #endif "trick" so you don't have to do it.
Of course, you should check... but anyways the compiler will tell you at some point ;-) It is anyhow a good practice to check for multiple inclusions since it slows down the compilation cycle.
During compilation preprocessor just replaces #include directive by specified file content.
To prevent endless loop it should use
#ifndef SOMEIDENTIFIER
#define SOMEIDENTIFIER
....header file body........
#endif
If some header was included into another header which was included to your file
than it is not necessary to explicitly include it again, because it will be included into the file recursively
Yes it is necessary or the compiler will complain when it tries to compile code that it is not "aware" of. Think of #include's are a hint/nudge/elbow to the compiler to tell it to pick up the declarations, structures etc in order for a successful compile. The #ifdef/#endif header trick as pointed out by jldupont, is to speed up compilation of code.
It is used in instances where you have a C++ compiler and compiling plain C code as shown here
Here is an example of the trick:
#ifndef __MY_HEADER_H__
#define __MY_HEADER_H__
#ifdef __cplusplus
extern "C" {
#endif
/* C code here such as structures, declarations etc. */
#ifdef __cplusplus
}
#endif
#endif /* __MY_HEADER_H__ */
Now, if this was included multiple times, the compiler will only include it once since the symbol __MY_HEADER_H__ is defined once, which speeds up compilation times.
Notice the symbol cplusplus in the above example, that is the normal standard way of coping with C++ compiling if you have a C code lying around.
I have included the above to show this (despite not really relevant to the poster's original question).
Hope this helps,
Best regards,
Tom.
PS: Sorry for letting anyone downvote this as I thought it would be useful tidbit for newcomers to C/C++. Leave a comment/criticisms etc as they are most welcome.
You need to include the header from your header, and there's no need to include it in the .c. Includes should go after the #define so they are not unnecessarily included multiple times. For example:
/* myHeader.h */
#ifndef MY_HEADER_H
#define MY_HEADER_H
#include <glib.h>
struct S
{
gchar c;
};
#endif /* MY_HEADER_H */
and
/* myCode.c */
#include "myHeader.h"
void myFunction()
{
struct S s;
/* really exciting code goes here */
}
I use the following construct to be sure, that the needed include file is included before this include. I include all header files in source files only.
#ifndef INCLUDE_FILE_H
#error "#include INCLUDE.h" must appear in source files before "#include THISFILE.h"
#endif
What I normally do is make a single include file that includes all necessary dependencies in the right order. So I might have:
#ifndef _PROJECT_H_
#define _PROJECT_H_
#include <someDependency.h>
#include "my_project_types.h"
#include "my_project_implementation_prototypes.h"
#endif
All in project.h. Now project.h can be included anywhere with no order requirements but I still have the luxury of having my dependencies, types, and API function prototypes in different headers.
Just include all external headers in one common header file in your project, e.g. global.h and include it in all your c files:
It can look like this:
#ifndef GLOBAL_GUARD
#define GLOBAL_GUARD
#include <glib.h>
/*...*/
typedef int YOUR_INT_TYPE;
typedef char YOUR_CHAR_TYPE;
/*...*/
#endif
This file uses include guard to avoid multiple inclusions, illegal multiple definitions, etc.