I'm trying to make a library file. The .cpp file has some conditional compiled lines. The code can be found at:
HMC58X3.h http://sprunge.us/hEYW
HMC58X3.cpp http://sprunge.us/faRN
HMC58X3_raw.pde http://spru开发者_JAVA百科nge.us/BFVj
Basically, in the Arduino sketch file HMC58X3_raw.pde
I define ISHMC5843 and in both HMC58X3.cpp
and HMC58X3.h
I do have different code to be compiled depending if that flag has been enabled.
The conditional compilation seems to work for HMC58X3.h
while it doesn't for HMC58X3.cpp
. It always looks as if ISHMC5843 hasn't been defined. How can it be made to work?
A #define
is not like a global variable. It's a pre-processor macro that only applies to the remaining text of that compile unit. There are a couple ways to do what you want:
- Create a
config.h
with#define ISHMC5843
and be sure to include it everywhere (and before any other includes that reference it). - In your
Makefile
(probably inaccessible to you in Arduino) ensure-DISHMC5843
appears on every compile line, typically by including it inCFLAGS
. (The details of how to ensureCFLAGS
is part of your compile rule is way beyond the scope of this question).
When you compile HMC58X3.cpp the compiler hasn't seen the macro definitions in HMC58X3_raw.pde. IMO, you're better of using a global boolean constant variable to achieve what you're trying to do here.
I cannot see how ISHMC58431
is defined in either HMC58X3.h or HMC58X3.cpp.
The definition has to be visible to the preprocessor when the file is pre-processed. This is normally done by #include
'ing a common file that includes the #define
in all files that need visibility of the macro, or by defining the macro on the compiler command line, such as -DISHMC58431
for example (compiler dependent).
This would of course require that the .pde file is also processed by the pre-processor, which since it has #include
statements, I assume that it is.
精彩评论