Marko Gulin
Marko Gulin

Reputation: 563

Macro statements used in a header file, but defined outside of it

I'm writing some libraries for a microcontroller, and I've organized these libraries in sections with respect to their function. For example, I have adc.h to configure analog input measurements, uart.h, and i2c.h for digital communication etc.

Some of these libraries need information on a CPU speed, so I've defined a macro statement

#define FCY 30000000UL

inside all header files that need this piece of information. My question is, can I program somehow these header files in a way that the FCY macro is only "declared" in the header file, but is defined outside of it, e.g. in a main.c file? The problem is, when I change the CPU speed (frequency), I have to update all these FCY macro statements, which is prone to error.

Upvotes: 1

Views: 1923

Answers (3)

Luis Colorado
Luis Colorado

Reputation: 12708

Well, perhaps the solution is to make FCY definition to depend on another macro definition where you have stored the SPEED info, like:

#define SPEED 345

and in other file

#define FCY 30000##SPEED##UL

That will substitute/expand FCY in your code by 30000345UL so you can change individually the SPEED macro and the FCY macro.

In case some formula is to be applied, you can do something like this:

#define SPEED 345

and in the cpu file:

#define FCY  (300000000UL | (SPEED)) 

Upvotes: 0

alk
alk

Reputation: 70981

Do not define FCY at all in any source-/header-file, but just when invoking the compiler.

For GCC you can do this using the option -D like this:

gcc src1.c src2.c main.c -o main -DFCY=30000000UL

This way the pre-processor "sees" FCY the way as #defined via option -D for all three files: src1.c, src2.c and main.c

Upvotes: 1

Stephan Lechner
Stephan Lechner

Reputation: 35164

I'd suggest to provide a separate header file like, for example, hardware_constants.h for things that need to be the same across several .h files or c-files. Include hardware_constants.h where needed instead of (re)defining the same thing many times.

You could even let the one invoking the compiler provide these definitions, e.g. at the command line, in your make-file, or in the project settings of your IDE.

And some IDEs provide headers that are automatically included before every translation unit. In XCode projects, for example, you can place common #define ...-statements in a file called PrefixHeader.pch, and these definitions will be implicitly available in every source code file.

Upvotes: 1

Related Questions