#define

I have this code

#define HMC5883_WriteAddress 0x1E
#define HMC5883_ModeRegisterAddress 0x02
#define HMC5883_ContinuousModeCommand 0x00
#define HMC5883_DataOutputXMSBAddress  0xs

I would like to put it on one line like this

#define HMC5883_WriteAddress 0x1E    #define HMC5883_ModeRegisterAddress 0x02    #define HMC5883_ContinuousModeCommand 0x00    #define HMC5883_DataOutputXMSBAddress  0xs

when I put my code like this the compiler says stray # in program. I am using 1.0.5

Separate #defines go on separate lines.

is there any work around? can I put them somewhere else in my code?

All preprocessor directives are terminated with a newline character instead of the semicolon statement termination character. This means any preprocessor directive must appear on its own line.

I would like to put it on one line like this

Why?

It’s generally better to define this sort of constant using ‘const byte’ instead of #define, and then you can put them all on one line:

const byte HMC5883_WriteAddress = 0x1E, HMC5883_ModeRegisterAddress = 0x02, HMC5883_ContinuousModeCommand = 0x00;

I’ve left out the last one because 0xs doesn’t make sense.

is there any work around? can I put them somewhere else in my code?

you can also create a separate MyHMC5883_defines.h file which has all the #defines one per line…

Instead of using #define you could declare them as static const byte, BUT it's much better (readable) to have those values in separate lines like in your original code.

JarkkoL:
Instead of using #define you could declare them as static const byte, BUT it's much better (readable) to have those values in separate lines like in your original code.

Why static?

dc42:
Why static?

It limits the variable scope to the translation unit thus compiler is allowed to do some optimizations on it.

JarkkoL:

dc42:
Why static?

It limits the variable scope to the translation unit thus compiler is allowed to do some optimizations on it.

The scope of “const int …” at file level has internal linkage (i.e. it is limited to the translation unit), so the compiler is at liberty to do the optimizations you refer to and ‘static’ would be redundant. See section 3.5 of the ISO C++ 2003 standard. Note that this is different from C, because in C such a declaration has external linkage. If you remove the ‘const’, then the declaration has external linkage in both C and C++.