0

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    
Buzz
  • 1,102
  • 1
  • 9
  • 24

1 Answers1

0

Your sample code compiles without issue. There has to be something going on that isn't included in your code here. My guess is you are either not compiling exactly what you think you are (we've all been there) or there's some macro magic going on in a header not included here.

digby280
  • 879
  • 1
  • 7
  • 22
  • My guilt not suitably searching for an existing solution. You're quite right: the compiler was compiling indipendently `main.cpp` and other headers! I edit my answer with the solution. Thank's a lot! – Buzz Mar 18 '18 at 16:56