I can't figured out what's wrong with the following code.
I'm building an AVR project in C++. I need to define some parameters that are to be used in different parts of the project. More specifically I want to define the CPU frequency in order to make some calculation in other parts of the project.
// ======= main.cpp ======
#define F_CPU 16000000UL
#include "MyDriver.h"
int main(void)
{
[...]
}
// ======= MyDriver.h =======
#ifndef MY_DRIVER_H_
#define MY_DRIVER_H_
#ifndef F_CPU
#error "Please define F_CPU in order to implement the driver"
#endif
#include <avr/io.h>
#include <avr/interrupt.h>
#endif
[...]
The compiler returns the error according to my #error
directive: in MyDriver.h
, F_CPU
is not defined.
Thinking about and speculating on the fact that the problem could be into the definition of F_CPU
inside main.cpp
, I thought to create a top-level config.h
header in order to include all global definitions:
// ======= main.cpp ======
#include "config.h"
#include "MyDriver.h"
int main(void)
{
[...]
}
// ======= config.h ========
#ifndef CONFIG_H_
#define CONFIG_H_
#define F_CPU 16000000UL
#endif
// ======= MyDriver.h =======
#ifndef MY_DRIVER_H_
#define MY_DRIVER_H_
#ifndef F_CPU
#error "Please define F_CPU in order to implement the driver"
#endif
#include <avr/io.h>
#include <avr/interrupt.h>
[...]
#endif
Nothing changed: MyDriver.h
is not able to see F_CPU
definition. I also used some pragmas to verify that the compiler would had run into config.h
and they confirmed so.
Any suggestion?
Thank's in advance
EDIT - SOLUTION
My guilt not searching suitably for a solution. Similar problem discussed in Macro defined in main.c not visible in another included file
So the way to use a config.h
was right, but I had to include config.h
from each headers, not from the main itself.
// ======= main.cpp ======
#include "MyDriver.h"
int main(void)
{
[...]
}
// ======= config.h ========
#ifndef CONFIG_H_
#define CONFIG_H_
#define F_CPU 16000000UL
#endif
// ======= MyDriver.h =======
#ifndef MY_DRIVER_H_
#define MY_DRIVER_H_
#include "config.h"
#ifndef F_CPU
#error "Please define F_CPU in order to implement the driver"
#endif
#include <avr/io.h>
#include <avr/interrupt.h>
[...]
#endif