Nate
Nate

Reputation: 259

Using numeric constant in macro function

I'm writing a simple library for my AVR, and I wanted to try to use a macro function to define my baud-rate. A lot of the functions in the AVR's library use the macro F_CPU as well as the one I want to write.

Here's what I have for the macro definition and my supposed implementation:

#define BAUD_SELECT(baud) ((F_CPU)/(2*baud)-1)

myubrr = BAUD_SELECT(38400);

I have tried using #define F_CPU 8000000UL, and also in the make file as -D"F_CPU 8000000UL" but I always get the same error at the implementation line.

expected ')' before numeric constant

I'm sure it has something to do with my abuse of #define, and that the macro definition is in a header file, the implementation in the appropriate .c file, and the F_CPU definition either in the makefile or another main.c file.

EDIT I made the parenthesis change as suggested and ran the preprocessor and found the output file (atleast I think)

 unsigned int myubrr = ((8000000UL 1)/(2*(baud))-1);

It places an extra 1 where F_CPU should be, I'm not experienced with the preprocessor so I'm not sure how to make it not do that, but perhaps that is the problem?

Upvotes: 0

Views: 907

Answers (2)

Chris Dodd
Chris Dodd

Reputation: 126243

This works fine for me:

#define BAUD_SELECT(baud) ((F_CPU)/(2*(baud))-1)

unsigned int myubrr = BAUD_SELECT(38400);

when I compile with

$ cc -c -DF_CPU=8000000UL t.c

The extra parens don't really matter in this specific case, thought they're a good idea in general. So there's something else going on. Perhaps there's another definition of F_CPU in some other header file that is overriding your definition of F_CPU

Upvotes: 0

sidyll
sidyll

Reputation: 59287

Try wrapping it in parentheses:

#define BAUD_SELECT(baud) ((F_CPU)/(2*(baud))-1)

Upvotes: 1

Related Questions