How to achieve a c++ macros like this - c++

#define idebug(...) \
\#ifdef _DEBUG\
printf(__VA_ARGS__);\
\#endif\
#endif
It is difficult to describe the intention,
which generally means that i predefine a macros idebug which to save some code.
If _ DEBUG flag is predefined, then print the output.
Or pretend nothing happened.
if we achieve it using a function ,it will look like this:
void idebug(...)
{
#ifdef _DEBUG
printf(...);
#endif
}
Suppose there is a program
int main()
{
int a = 10;
idebug("a:%d\n",a);
}
when we are in the debugging phase, we want a output by complier:
int main()
{
int a = 10;
printf("a:%d\n",a);
}
if we are in the release phase, we want a output by complier:
int main()
{
int a = 10;
}

Do it the other way:
#ifdef _DEBUG
# define idebug(...) printf(__VA_ARGS__)
#else
# define idebug(...) ((void)0)
#endif

Related

Disabling assert macro in C++

I'm trying to disable the assert macro in C++ in this way:
#include <stdio.h> /* printf */
#include <assert.h> /* assert */
#define NDEBUG
void print_number(int* myInt) {
assert (myInt != NULL);
printf ("%d\n", *myInt);
}
int main ()
{
int a = 10;
int * b = NULL;
int * c = NULL;
b = &a;
print_number (b);
print_number (c);
return 0;
}
The official website says that if I define NDEBUG, all the assert macro will be disable. This way doesn't work. Can you tell me how fix it?
The NDEBUG define controls the definition of the assert macro, not its expansion. In order for it to be effective, you need to define it before the macro itself is defined, which happens in assert.h.
There are two ways to achieve that:
put the #define NDEBUG before the line that says #include <assert.h>; or
define NDEBUG on the command line, by doing something like:
cc -DNDEBUG main.c
Perhaps you should also take a step back and consider why you are trying to disable assertions. After all, the assertions are there for a reason, so unless you are running on a 40MHz SPARCstation, you should probably not be disabling them.

Get a different value with macro every time it's used [duplicate]

I'm writing a bunch of related preprocessor macros, one of which generates labels which the other one jumps to. I use them in this fashion:
MAKE_FUNNY_JUMPING_LOOP(
MAKE_LABEL();
MAKE_LABEL();
)
I need some way to generate unique labels, one for each inner MAKE_LABEL call, with the preprocessor. I've tried using __LINE__, but since I call MAKE_LABEL inside another macro, they all have the same line and the labels collide.
What I'd like this to expand to is something like:
MAKE_FUNNY_JUMPING_LOOP(
my_cool_label_1: // from first inner macro
...
my_cool_label_2: // from second inner macro
...
)
Is there a way to generate hashes or auto-incrementing integers with the preprocessor?
If you're using GCC or MSVC, there is __COUNTER__.
Other than that, you could do something vomit-worthy, like:
#ifndef USED_1
#define USED_1
1
#else
#ifndef USED_2
#define USED_2
2
/* many many more */
#endif
#endif
I use this:
#define MERGE_(a,b) a##b
#define LABEL_(a) MERGE_(unique_name_, a)
#define UNIQUE_NAME LABEL_(__LINE__)
int main()
{
int UNIQUE_NAME = 1;
return 0;
}
... and get the following:
int main()
{
int unique_name_8 = 1;
return 0;
}
As others noted, __COUNTER__ is the easy but nonstandard way of doing this.
If you need extra portability, or for other cool preprocessor tricks, the Boost Preprocessor library (which works for C as well as C++) will work. For example, the following header file will output a unique label wherever it's included.
#include <boost/preprocessor/arithmetic/inc.hpp>
#include <boost/preprocessor/slot/slot.hpp>
#if !defined(UNIQUE_LABEL)
#define UNIQUE_LABEL
#define BOOST_PP_VALUE 1
#include BOOST_PP_ASSIGN_SLOT(1)
#undef BOOST_PP_VALUE
#else
#define BOOST_PP_VALUE BOOST_PP_INC(BOOST_PP_SLOT(1))
#include BOOST_PP_ASSIGN_SLOT(1)
#undef BOOST_PP_VALUE
#endif
BOOST_PP_CAT(my_cool_label_, BOOST_PP_SLOT(1)):
Sample:
int main(int argc, char *argv[]) {
#include "unique_label.h"
printf("%x\n", 1234);
#include "unique_label.h"
printf("%x\n", 1234);
#include "unique_label.h"
return 0;
}
preprocesses to
int main(int argc, char *argv[]) {
my_cool_label_1:
printf("%x\n", 1234);
my_cool_label_2:
printf("%x\n", 1234);
my_cool_label_3:
return 0;
}
I can't think of a way to automatically generate them but you could pass a parameter to MAKE_LABEL:
#define MAKE_LABEL(n) my_cool_label_##n:
Then...
MAKE_FUNNY_JUMPING_LOOP(
MAKE_LABEL(0);
MAKE_LABEL(1);
)
You could do this:
#define MAKE_LABEL() \
do { \
my_cool_label: \
/* some stuff */; \
goto my_cool_label; \
/* other stuff */; \
} while (0)
This keeps the scope of the label local, allowing any number of them inside the primary macro.
If you want the labels to be accessed more globally, it's not clear how your macro "MAKE_FUNNY_JUMPING_LOOP" references these labels. Can you explain?
It doesn't seem possible with a standard preprocessor, although you could fake it out by putting parameters within MAKE_LABEL or MAKE_FUNNY_JUMPING_LOOP, and use token pasting to create the label.
There's nothing preventing you from making your own preprocessing script that does the automatic increment for you. However, it won't be a standard C/C++ file in that case.
A list of commands available: http://www.cppreference.com/wiki/preprocessor/start

Disable multiline statements with c/c++ macro

Is it possible to disable chunks of code with c/c++ preprocessor depending on some definition, without instrumenting code with #ifdef #endif?
// if ENABLE_TEST_SONAR is not defined, test code will be eliminated by preprocessor
TEST_BEGIN(SONAR)
uint8_t sonar_range = get_sonar_measurement(i);
TEST_ASSERT(sonar_range < 300)
TEST_ASSERT(sonar_range > 100)
TEST_END
Functionally equivalent to something as follows:
#ifdef TEST_SONAR
serial_print("test_case sonar:\r\n");
uint8_t sonar_range = get_sonar_measurement(i);
serial_print(" test sonar_range < 300:%d\r\n", sonar_range < 300);
serial_print(" test sonar_range > 100:%d\r\n", sonar_range > 100);
#endif TEST_SONAR
Multiple lines can be disabled only with #ifdef or #if but single lines can be disabled with a macro. Note that multiple lines can be combined with \
#ifdef DOIT
#define MYMACRO(x) \
some code \
more code \
even more \
#else
#define MYMACRO(x)
#endif
Then when you call MYMACRO anplace that code will either be included or not based on whether DOIT is defined
That's the closest you can come and is used frequently for debugging code
EDIT: On a whim I tried the following and it seems to work (in MSVC++ and g++):
#define DOIT
#ifdef DOIT
#define MYMACRO(x) x
#else
#define MYMACRO(x)
#endif
void foo(int, int, int)
{
}
int main(int, char **)
{
int x = 7;
MYMACRO(
if (x)
return 27;
for (int i = 0; i < 10; ++i)
foo(1, 2, 3);
)
}
No, the only way to disable sections of codes effectively using preprocessing is by #ifdef #endif. Theoretically, you could use #if identifier, but it's better to stick to checking whether a variable is defined.
Another option (perhaps) is to use a preprocessing macro:
Edit:
Perhaps using plain functions and #ifdef might work better?
function test_function() {
/* Do whatever test */
}
#define TESTING_IDENTIFIER
#define TEST( i, f ) if ((i)) do { f } while (0)
Then, for each test, you define a unique identifier and call it by providing the identifier first and the function (with parenthesis) second.
TEST( TESTING_IDENTIFIER, test_function() );
Finally, f can be anything that's syntactically correct -- You don't have to create a function for every test, you can put the code inline.
I will anyway mention an obvious solution of
#define DO_TEST_SONAR
#ifdef DO_TEST_SONAR
#define TEST_SONAR if(true) {
#else
#define TEST_SONAR if(false) {
#endif
#define TEST_SONAR_END }
...
TEST_SONAR
code
TEST_SONAR_END
The code will still get compiled, not completely removed, but some smart compilers might optimize it out.
UPD: just tested and
#include <iostream>
using namespace std;
//#define DO_TEST_SONAR
#ifdef DO_TEST_SONAR
#define TEST_SONAR if(true) {
#else
#define TEST_SONAR if(false) {
#endif
#define TEST_SONAR_END }
int main() {
TEST_SONAR
cout << "abc" << endl;
TEST_SONAR_END
}
produces absolutely identical binaries with cout line commented out and non commented, so indeed the code is stripped. Using g++ 4.9.2 with -O2.

#define leads to the "Access violation reading location"

I think this is child question but i can't find info how to solve it.
//*.h:
class Foo
{
#if defined(RedefChallangesCount)
static const mainDataType ChallangesCount = 500;
#undef RedefChallangesCount
#else
static const mainDataType ChallangesCount = 1;
#endif
...
int _correctAnswers[ChallangesCount];
....
}
In my VS tests class:
#include "stdafx.h"
#include "CppUnitTest.h"
#define RedefChallangesCount
#include "..\Core\ChallengeManager.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
using namespace Brans;
namespace CoreTests
{
TEST_CLASS(SomeTestClass)
{
public:
TEST_METHOD(SomeTestMethod)
{
Foo* cm = new Foo();
cm->Method();
...
delete cm;
}
}
}
It seems for me that i do all like in docs, but when run test with #define RedefChallangesCount line i got strange errors like "Access violation reading location", sometimes bad array
_correctAnswers. At the same time i see that ChallangesCount is 500 as expected. If i comment #define RedefChallangesCount line - all errors gone...
What can be wrong?
Your #undef makes me suspicious that this header is being included elsewhere (e.g by ChallengeManager.cpp, meaning you'll end up with your _correctAnswers having a size of 500 in some places and 1 in others, which would certainly explain your crash.
(edit): Are your tests a separate project in the solution, with the main code in its own project, or is your code all compiled directly in the test project?
To be safe, set your #define in the VS build configuration (for all projects being linked into the tests - you'll need to add a Tests build config for this, and use it instead of Debug/Release for the test build) rather than defining it in code, and remove the #undef
I tend not to have if defined sections within code, especially class code. I would tend to use a variable, and branch based on its value:
in the test class remove the #define RedefChallangesCount and replace with a global variable of bool RedefChallangesCount
Then your code becomes much simpler and can be as follows (simplified version for demonstration purposes):
#include <iostream>
using namespace std;
bool RedefChallangesCount = false;
int main()
{
int ChallangesCount;
cout << RedefChallangesCount << endl;
if (RedefChallangesCount)
ChallangesCount = 500;
else
ChallangesCount = 1;
cout << ChallangesCount << endl;
return 0;
}
as opposed to:
#if defined(RedefChallangesCount)
static const mainDataType ChallangesCount = 500;
#undef RedefChallangesCount
#else
static const mainDataType ChallangesCount = 1;
#endif
However, let me know if using preprocessor is a requirement and then I can try and sort you out a solution using that methodology, though as I said, I don't use preprocessor directives for actual program flow (have to add normally, as guaranteed I have done it once for a valid reason, and cant remember).

Is there a neat method to output text to debugging pane?

I would like to display some log messages when debugging. One option is to use the very ugly
#ifdef DEBUG
std::cout << "I'm in debug mode!\n";
#endif
In the JUCE library, there is a nice macro that outputs text to the debugging pane
DBG("I'm in debug mode!")
The juce solution also allows you to do neat stuff like the following that would be desirable
int x = 4;
DBG(String("x=") + String(x))
I would like to know if a similarly neat method exists in std:: or boost::
Why not just write your own:
#ifdef DEBUG
#define DBG(x) std::cout << x;
#else
#define DBG(x)
#endif
For namespaces
namespace DBG
{
inline void DBG(const char* x)
{
#ifdef DEBUG
std::cout << x;
#endif
}
}
If you want something like printf, you should use a bit another macros:
void DebugPrintLn(const char* format, ...);
inline void Nothing(...) {}
#ifdef DEBUG
#define DBG DebugPrintLn
#else
#define DBG Nothing // Or __noop on Visual C++
#endif
Using Nothing is portable, but arguments still computed (__noop guarantees that any of argument will be not computed, VC++ specific). Better if you can use macros variable arguments (both available on GCC and latest VC++): you may even skip any argument computation in portable way:
#ifdef DEBUG
#define DBG(...) DebugPrintLn(__VAR_ARGS__)
#else
#define DBG(...) ((void)0)
#endif
In any case, you use it the same way:
DBG("Lucky day: %s %i", "Friday", 13);
I have also written my own portable TRACE macro. I share it here:
#ifdef ENABLE_TRACE
# ifdef _MSC_VER
# include <windows.h>
# include <sstream>
# define TRACE(x) \
do { std::stringstream s; s << (x); \
OutputDebugString(s.str().c_str()); \
} while(0)
# else
# include <iostream>
# define TRACE(x) std::clog << (x)
# endif // or std::cerr << (x) << std::flush
#else
# define TRACE(x)
#endif
example:
#define ENABLE_TRACE //can depend on _DEBUG or NDEBUG macros
#include "my_above_trace_header.h"
int main (void)
{
int v1 = 123;
double v2 = 456.789;
TRACE ("main() v1="<< v1 <<" v2="<< v2 <<'\n');
}
Any improvements/suggestions/contributions are welcome ;-)