I'm programming an Arduino sketch in C++. I want the user to be able to #definea constant directly in the sketch.ino file which will be needed to compile the code. The Arduino IDE uses a g++ compiler.
Let's assume we have three files:
sketch.ino
sketch.h
sketch.cpp
In sketch.h I defined
#define OPTION_1 0
#define OPTION_2 1
#define OPTION_3 2
#define OPTION_4 3
#define SLOW 0
#define FAST 1
In sketch.ino the user then defines MYOPTION:
#define MYOPTION OPTION_2
In sketch.h I use the variable to define macros:
#if MYOPTION == OPTION_1 | MYOPTION == OPTION_2
#define SPEED FAST
#else
#define SPEED SLOW
#endif
In sketch.cpp I use it to improve time critical code:
MyClass::foo() {
// do something
#if SPEED == FAST
// do more
#if MYOPTION == OPTION_2
// do something extra
#endif
#endif
#if MYOPTION == OPTION_4
// do something else
#endif
}
Unfortunately the definition of MYOPTION doesn't seem to be recognized inside sketch.cpp. Hower sketch.cpp does recognize variables defined in sketch.h. Is there a way to define preprocessor variables globally, so they can be accessed in any file that uses them?
Move the option definitions to a separate file, e.g. options.h. You could also define them in sketch.ino if you like.
Include options.h in sketch.ino and sketch.h.
Move all the code that relies on the MYOPTION macro from sketch.cpp to sketch.h.
Define MYOPTION in sketch.ino before including sketch.h:
#include "options.h"
#define MYOPTION OPTION_2
#include "sketch.h"
Here's an example of a popular library that uses this technique:
https://github.com/PaulStoffregen/Encoder
It allows the user to configure the use of interrupts from the sketch via the ENCODER_DO_NOT_USE_INTERRUPTS and ENCODER_OPTIMIZE_INTERRUPTS macros.
I have something like this in header.h:
#ifdef SOME_MACRO
#define MACRO_A
//Some code 1
#else
#define MACRO_A
//Some code 2
#endif
In main.cpp:
#include "header.h"
#define SOME_MACRO
...
MACRO_A; //It should be Some code 1
Is there a way to make SOME_MACRO definition in main.cpp affect header.h?
Putting #define SOME_MACRO before the header doesn't make changes.
First, yes you have to put the definition of your selector before the include statement:
#define SOME_MACRO // <<<<<<<<<<<<<<<<<<<<<<<
#include "header.h"
Second, if I take your sample literally, you probably missed that all code in a macro definition needs to go in a single line:
#ifdef SOME_MACRO
// Note the escaped line endings below: \
#define MACRO_A \
//Some code 1
#else
#define MACRO_A \
//Some code 2
#endif
I have a problem where I can't seem to get conditional #define preprocessors to work correctly. For example:
#define WIN32_BUILD
#ifdef WIN32_BUILD
#define PCH "stdafx.h"
#else
#define PCH "xyz.h"
#endif
#include PCH
If I use this form, the compiler tells me that it can't find 'stdafx.h'. OK, that seems odd, so if I change the code to....
#define WIN32_BUILD
#ifdef WIN32_BUILD
#define PCH "xyz.h"
#else
#define PCH "stdafx.h"
#endif
#include PCH
Then the file defined in PCH gets picked up and everything compiles fine. This seems odd to me, almost like the preprocessor is ignoring the #if directives and just using all the #defines that it encounters.
Obviously I am doing something wrong, and I was hoping that someone could help me understand this.
When a project has the precompiled header feature turned on the preprocessor ignores everything that comes before #include "stdafx.h"
So your #define statements are ignored.
TL:DR; #define defines the symbol, #ifdef tests if the symbol is defined not whether it has a value.
#define WIN32_BUILD
This defines a pre-processor token, WIN32_BUILD. The token has no value. Anywhere you use the token 'WIN32_BUILD' the pre-processor will substitute the empty string, i.e. nothing.
#ifdef WIN32_BUILD
This checks if the pre-processor token WIN32_BUILD is defined. It is, you just defined it.
#ifdef WIN32_BUILD
// true - this code is included.
#define PCH "stdafx.h"
This defines the pre-processor token, PCH, and assigns it the value "stdafx.h"
#else
#define PCH "xyz.h"
#endif
This code is ignored, because WIN32_BUILD was defined.
It looks as though you were expecting 'ifdef' to only evaluate to true if the expression was not defined /to/ something.
#define a
#define b SOMETHING
#ifdef a
// you are expecting this to be ignored
#endif
#ifdef b
// and expecting this not to be ignored
#endif
#ifdef and #if defined(...) do the same thing.
#define a
#define b SOMETHING
#if defined(a) && defined(b)
// this code will be evaluated, both tokens are defined.
#endif
This feature of pre-processor tokens is often used to support conditional functionality:
#if HAVE_CPP11_OVERRIDE_KEYWORD
#define OVERRIDE_FN override
#else
#define OVERRIDE_FN
#endif
struct A {
virtual void foo() {}
};
struct B : public A {
void foo() OVERRIDE_FN {}
};
In the above code, the override keyword is only added if the system supports it (determined outside of the code).
So a compiler with override sees
struct B : public A {
void foo() override {}
};
a compiler without it sees
struct B : public A {
void foo() {}
};
Note: The opposite of "ifdef" is "ifndef":
#define a
#define b SOMETHING
#undef c
//#define d // << we didn't define it.
int main() {
#ifdef a
#pramga message("a is defined")
#else
#pramga message("a is UNdefined")
#endif
#ifdef b
#pragma message("b is defined")
#else
#pramga message("b is UNdefined")
#endif
#ifdef c
#pramga message("c is defined")
#endif
#else
#pramga message("c is UNdefined")
#endif
#ifdef d
#pramga message("d is defined")
#endif
#else
#pramga message("d is UNdefined")
#endif
#ifndef d
#pragma message("d is not defined")
#endif
#ifndef a
#pragma message("a is not defined")
#endif
return 0;
}
You can assign a pre-processor token numeric values and test them with #if
#if _MSC_VER
#define WIN32_BUILD 1
#else
#define WIN32_BUILD 0
#endif
#if WIN32_BUILD
#include <Windows.h>
#endif
But, especially when doing cross-platform programming, people tend to use ifdef variants rather than numeric checks, because the value checks require you to explicitly ensure all of the tokens are defined with a value. It's a lot easier just to only define them when you need them.
I'm building a C++ DLL for one of my projects. I am trying to standardize the way that are class are defined. So instead of each time writing:
class __declspec(dllexport) ClassName
I'm building a #define macro to ease this process:
#define CLASS( cName ) class __declspec(dllexport) cName
But, when I'm using it, it gives me the following error:
Error: Expected a ';'
I know you can use a #define macro to define an entire class creation, but can it be used to define only the "class header" ?
Thanks,
Keep in mind that I'm trying to do so because we are going to deal with hundreds of classes, so these kinds of "automation" would be most helpful :)
EDIT:
example:
#define CLASS( nClass ) class __declspec(dllexport) nClass
CLASS( APTest )
{ // Here is the error of missing ';'
public:
APTest();
};
Don't do this.
C++ has already been standardized!
If you ever expect other people to read your code then just write it in conventional C++, not some homecooked dialect that looks different. Get used to the proper C++ syntax, it will make it easier to read other people's C++ code.
One thing that does make sense is to simplify the __declspec part, which you can do like this:
#ifdef _WIN32
#define DLLEXPORT __declspec(dllexport)
#else
#define DLLEXPORT
#endif
class DLLEXPORT APTest
{
// ...
};
You're really not making your life any simpler by writing CLASS( APTest ) and you make it harder for others to understand. Just say no.
There is a better way than #Wakely. Do it like this:
#ifdef MYLIB_DLL
#ifndef MYLIB_IFACE
#ifdef MYLIB_IFACE_EXPORT
#define MYLIB_IFACE _declspec( dllexport )
#else // !MYLIB_IFACE_EXPORT
#define MYLIB_IFACE _declspec( dllimport )
#endif // !MYLIB_IFACE_EXPORT
#endif // !MYLIB_IFACE
#else // !MYLIB_DLL
#ifndef MYLIB_IFACE
#define MYLIB_IFACE
#endif // !MYLIB_IFACE
Put a block like that in a header that is used by every file in your dll, and in the public header for your dll.
Every symbol that should be exported from your dll gets tagged like this:
class MYLIB_IFACE MyClass
{
};
void MYLIB_IFACE myFunc();
Then in every .cpp file in your dll the first line should be:
#define MYLIB_IFACE_EXPORT
If you do this, then it will build just fine on POSIX systems that don't use dllexport/dllimport. To build a dll version of your lib you define MYLIB_DLL. ( you can do this in the compiler's flags so it can be controlled from your build system )
To build a static version of your lib, don't define MYLIB_DLL.
#Update:
You can extend this to support GCC visilibity like this:
#ifdef WIN32
#define KX_SYMBOL_EXPORT _declspec( dllexport )
#define KX_SYMBOL_IMPORT _declspec( dllimport )
#else // GCC
#define KX_SYMBOL_EXPORT __attribute__(( visibility ("default")))
#define KX_SYMBOL_IMPORT
#endif
#ifdef KX_DLL
#ifndef KX_IFACE
#ifdef KX_IFACE_EXPORT
#define KX_IFACE KX_SYMBOL_EXPORT
#else // !KX_IFACE_EXPORT
#define KX_IFACE KX_SYMBOL_IMPORT
#endif // !KX_IFACE_EXPORT
#endif // !KX_IFACE
#else // !KX_DLL
#ifndef KX_IFACE
#define KX_IFACE
#endif // !KX_IFACE
#endif // !KX_DLL
I remove the GCC bit in the first example for simplicity. But this is how a really do it. #Wakely is so right.
I have encountered the #define pre-processor directive before while learning C, and then also encountered it in some code I read. But apart from using it to definite substitutions for constants and to define macros, I've not really understook the special case where it is used without a "body" or token-string.
Take for example this line:
#define OCSTR(X)
Just like that! What could be the use of this or better, when is this use of #define necessary?
This is used in two cases. The first and most frequent involves
conditional compilation:
#ifndef XYZ
#define XYZ
// ...
#endif
You've surely used this yourself for include guards, but it can also be
used for things like system dependencies:
#ifdef WIN32
// Windows specific code here...
#endif
(In this case, WIN32 is more likely defined on the command line, but it
could also be defined in a "config.hpp" file.) This would normally
only involve object-like macros (without an argument list or
parentheses).
The second would be a result of conditional compilation. Something
like:
#ifdef DEBUG
#define TEST(X) text(X)
#else
#define TEST(X)
#endif
That allows writing things like:
TEST(X);
which will call the function if DEBUG is defined, and do nothing if it
isn't.
Such macro usually appears in pair and inside conditional #ifdef as:
#ifdef _DEBUG
#define OCSTR(X)
#else
#define OCSTR(X) SOME_TOKENS_HERE
#endif
Another example,
#ifdef __cplusplus
#define NAMESPACE_BEGIN(X) namespace X {
#define NAMESPACE_END }
#else
#define NAMESPACE_BEGIN(X)
#define NAMESPACE_END
#endif
One odd case that I recently dug up to answer a question turned out to be simply commentary in nature. The code in question looked like:
void CLASS functionName(){
//
//
//
}
I discovered it was just an empty #define, which the author had chosen to document that the function accessed global variables in the project:
C++ syntax: void CLASS functionName()?
So not really that different from if it said /* CLASS */, except not allowing typos like /* CLAAS */...some other small benefits perhaps (?)
I agree with every answer, but I'd like to point out a small trivial thing.
Being a C purist I've grown up with the assertion that EACH AND EVERY #define should be an expression, so, even if it's common practice using:
#define WHATEVER
and test it with
#ifdef WHATEVER
I think it's always better writing:
#define WHATEVER (1)
also #debug macros shall be expressions:
#define DEBUG (xxx) (whatever you want for debugging, value)
In this way, you are completely safe from misuse of #macros and prevents nasty problems (especially in a 10 million line C project)
This can be used when you may want to silent some function. For example in debug mode you want to print some debug statements and in production code you want to omit them:
#ifdef DEBUG
#define PRINT(X) printf("%s", X)
#else
#define PRINT(X) // <----- silently removed
#endif
Usage:
void foo ()
{
PRINT("foo() starts\n");
...
}
#define macros are simply replaced, literally, by their replacement text during preprocessing. If there is no replacement text, then ... they're replaced by nothing! So this source code:
#define FOO(x)
print(FOO(hello world));
will be preprocessed into just this:
print();
This can be useful to get rid of things you don't want, like, say, assert(). It's mainly useful in conditional situations, where under some conditions there's a non-empty body, though.
As you can see in the above responses, it can be useful when debugging your code.
#ifdef DEBUG
#define debug(msg) fputs(__FILE__ ":" (__LINE__) " - " msg, stderr)
#else
#define debug(msg)
#endif
So, when you are debugging, the function will print the line number and file name so you know if there is an error. And if you are not debugging, it will just produce no output
There are many uses for such a thing.
For example, one is for the macro to have different behavior in different builds. For example, if you want debug messages, you could have something like this:
#ifdef _DEBUG
#define DEBUG_LOG(X, ...) however_you_want_to_print_it
#else
#define DEBUG_LOG(X, ...) // nothing
#endif
Another use could be to customize your header file based on your system. This is from my mesa-implemented OpenGL header in linux:
#if !defined(OPENSTEP) && (defined(__WIN32__) && !defined(__CYGWIN__))
# if defined(__MINGW32__) && defined(GL_NO_STDCALL) || defined(UNDER_CE) /* The generated DLLs by MingW with STDCALL are not compatible with the ones done by Microsoft's compilers */
# define GLAPIENTRY
# else
# define GLAPIENTRY __stdcall
# endif
#elif defined(__CYGWIN__) && defined(USE_OPENGL32) /* use native windows opengl32 */
# define GLAPIENTRY __stdcall
#elif defined(__GNUC__) && (__GNUC__ * 100 + __GNUC_MINOR__) >= 303
# define GLAPIENTRY
#endif /* WIN32 && !CYGWIN */
#ifndef GLAPIENTRY
#define GLAPIENTRY
#endif
And used in header declarations like:
GLAPI void GLAPIENTRY glClearIndex( GLfloat c );
GLAPI void GLAPIENTRY glClearColor( GLclampf red, GLclampf green, GLclampf blue, GLclampf alpha );
GLAPI void GLAPIENTRY glClear( GLbitfield mask );
...
(I removed the part for GLAPI)
So you get the picture, a macro that is used in some cases and not used in other cases could be defined to something on those cases and nothing to those other cases.
Other cases could be as follows:
If the macro doesn't take parameters, it could be just to declare some case. A famous example is to guard header files. Another example would be something like this
#define USING_SOME_LIB
and later could be used like this:
#ifdef USING_SOME_LIB
...
#else
...
#endif
Could be that the macro was used at some stage to do something (for example log), but then on release the owner decided the log is not useful anymore and simply removed the contents of the macro so it becomes empty. This is not recommended though, use the method I mentioned in the very beginning of the answer.
Finally, it could be there just for more explanation, for example you can say
#define DONT_CALL_IF_LIB_NOT_INITIALIZED
and you write functions like:
void init(void);
void do_something(int x) DONT_CALL_IF_LIB_NOT_INITIALIZED;
Although this last case is a bit absurd, but it would make sense in such a case:
#define IN
#define OUT
void function(IN char *a, OUT char *b);