Skip to content

Instantly share code, notes, and snippets.

@aaronsnoswell
Last active January 11, 2018 06:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aaronsnoswell/55ecd979fcd6b76132bca6e734081edd to your computer and use it in GitHub Desktop.
Save aaronsnoswell/55ecd979fcd6b76132bca6e734081edd to your computer and use it in GitHub Desktop.
Minimal test-case for undefined compiler behaviour when using the C/C++ defined() operator
/**
* Simple testcase for compiler-specific behaviour with the defined() C++ operator
* The spec states that if defined() appears as part of macro expansion, the behaviour is undefined
*
* On GNU cpp treats it as a genuine define() operator. Visual C++ doensn't.
* This generates many warnings when compiling e.g. the BSON library under Windows
*
* See https://gcc.gnu.org/onlinedocs/cpp/Defined.html for details
*
* On Visual C++ this program generates the following;
*
* > Test case for define() operator
* > (1) Fooey is not defined
* > (2) Fooey is not defined
* > (3) Fooey is defined
* > (4) Fooey is not defined
*
* On GNU C apparently older versions would have compiled this O.K, but given
* a -Wexpansion-to-defined warning. As of 5.4.0 I get a compiler error;
* error: operator "defined" requires an identifier
*
*/
#include <iostream>
#define DEFINED_MACRO(test) (defined(test))
int main(int argc, char **argv)
{
std::cout << "Test case for define() operator" << std::endl;
#if defined(FOOEY)
std::cout << "(1) Fooey is defined" << std::endl;
#else
std::cout << "(1) Fooey is not defined" << std::endl;
#endif
#if DEFINED_MACRO(FOOEY)
std::cout << "(2) Fooey is defined" << std::endl;
#else
std::cout << "(2) Fooey is not defined" << std::endl;
#endif
#define FOOEY 1
#if defined(FOOEY)
std::cout << "(3) Fooey is defined" << std::endl;
#else
std::cout << "(3) Fooey is not defined" << std::endl;
#endif
#if DEFINED_MACRO(FOOEY)
std::cout << "(4) Fooey is defined" << std::endl;
#else
std::cout << "(4) Fooey is not defined" << std::endl;
#endif
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment