'Using Definitions in C Header Files?

I'm currently learning the C programming language (coming from Java) and I'm a bit confused as to how to define a macro.

In order for other code to use the macro, the header file must have it. But if I define the macro in the header file, then the source file can't use it. Do I have to define it in both or do I have to #include the source file's own header file?



Solution 1:[1]

First #include is essentially like directly inserting the file in your file. It is run by the compiler pre-processor, which is run before the compiler. Google C preprocessor for more info...

Typically setup is:

#include "macros.h"

...

printf("Macro value %d\n", MACRO_HERE(1) );

and in your header file, macros.h

#ifndef MACROS_H_
#define MACROS_H_

#define MACRO_HERE( n ) ( n + 1 )

#endif

The wrapped #ifdef(s) prevent the macro from being redefined if you later have another include file which also includes macro.h

See also: #pragma once (which is widely used in many compilers also)

Solution 2:[2]

You can define it both in the header or the implementation file, but it needs to be visible to the translation unit you use it in.

If it's for use just inside one implementation file, define it in that file only.

If more files use the macro, define it in a header and include that header wherever you need the macro.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yun
Solution 2 Luchian Grigore