Is it possible to replace the whole line with #define? - c++

Let's assume that I have a program with many files and many cout's, and for debug purposes I would like to disable output for a moment, but only in a single file.
It is just out of curiosity question, I know that I shouldn't do that to disable output, but I started to wonder when facing this problem, and it only shows properly what I mean.
I tried to create a #define macro, but I can't replace the whole line, only a single symbol (with params).
For example:
//some common header file
#ifdef DISABLE_OUTPUT
#define cout... void; //?? DK exactly what should i put here
#endif
//other file
#include "commons.h" //my macro
#define DISABLE_OUTPUT
void foo()
{
...
cout << "blablabla" << 4 << "something" << endl; // should be removed
...
}
If DISABLE_OUTPUT is defined, the whole line should be replaced with void; (better clear the line).
The problem is that I don't know how to clear the whole line with #define.
Is there any "magic" symbol or trick that I can use?

It’s a bad idea to define a macro with the same name as a standard library component, so you shouldn’t #define cout at all. I’m going to assume you #define disableable_cout instead.
The simplest answer would be to define it like this:
#ifdef DISABLE_OUTPUT
#define disableable_cout if (false) cout
#else
#define disableable_cout cout
#endif
And then update the cout line in foo to this:
disableable_cout << "blablabla" << 4 << "something" << endl;
Which would expand to either this:
if (false) cout << "blablabla" << 4 << "something" << endl;
if DISABLE_OUTPUT is defined, or to this:
cout << "blablabla" << 4 << "something" << endl;
if DISABLE_OUTPUT were not defined.
Then, if DISABLE_OUTPUT is defined, the output line is skipped; if not, it will happen.
Alternately, you could require DISABLE_OUTPUT is always defined, to either 0 (don’t disable) or 1 (do disable). Then you could use a single definition, like this:
#define disableable_cout if (!DISABLE_OUTPUT) cout
Note that, either option is fragile, like most macros, but it should work in the typical case.

Related

Pre-processor parsing on C++

If we want to use user input to do something in a program, or print a result we need to
#include <iostream>
otherwise, cout and cin will not be acknowledged by the compiler.However the command #include is a pre-processor command. And when I was writing my program the following happened. I wrote the following code :
#define PRINT_DEBUG_INFO(a) {cout << “Info: ” << a << endl;}
#include <iostream>
And no errors popped up.How is it possible to use cout before including iostream? Even if I declare the PRINT_DEBUG_INFO(a) without including iostream, I don't get a compiling error.
Can somebody explain me why this happens?
The preprocessor doesn't require any C++ declared symbols to be evaluated to do its work.
It's pure text processing, so defining a macro like
#define PRINT_DEBUG_INFO(a) {cout << “Info: ” << a << endl;}
and expanding it like
#include <iostream>
void foo {
int a = 5;
PRINT_DEBUG_INFO(a);
}
will become
// All the literal stuff appearing in <iostream>
void foo {
int a = 5;
{cout << “Info: ” << a << endl;};
}
So there's nothing checked regarding proper C++ syntax during definition or expansion of the macro.
These statements will be processed further by the C++ compiler, which will complain about cout isn't declared in the global scope.
To fix this, declare your macro like
#define PRINT_DEBUG_INFO(a) {std::cout << “Info: ” << a << std::endl;}
You define PRINT_DEBUG_INFO but you don't use it so there is nothing for the compiler to compile or complain about.
You are just defining PRINT_DEBUG_INFO(a) and not using it. When you actually use it inside your program you will get the error that cout is not defined.
When you are not actually using it, the compiler finds no place to substitute the defined constant. When you actually use it, the program gets expanded during compilation and shows you the error.
And moreover there is a bracket in your macro which gets expanded with brackets and may lead to error.

Exclude line from compilation via Makro C++

I've got some problem, which might be simple to solve.
I have code like this:
#define _MG_ALL //This might be defined in some other headerfile
#ifndef _MG_ALL
#define MG_ALL <?????>
#else
#define MG_ALL <nothing>
#endif
In the code it is used like this:
ALL foo = thisIsSomeFunc(foo);
This line should only be compiled, if _ALL is defined. This could also be solved by using this:
#ifdef ALL
foo = thisIsSomeFunc(int foo);
#endif
But I would prefer just one short macro in the same line.
What you could do is defining the macro like so:
#ifdef _ALL
#define ALL if(1)
#else
#define ALL if(0)
#endif
When you use it this it will produce code similar to this
ALL std::cout << "Debug Message" << std::endl;
==> if(1) std::cout << "Debug Message" << std::endl;
A good compiler should recognize the constant value in the if-statement and should only compile the right part (1 ==> if part, 0 ==> nothing).

Using/Copying the value of a macro variable in/to a macro function before undefining it: is it possible?

If I have:
#define A 1
#define B() A
#undef A
This code:
#if B()
std::cout << "B" << std::endl;
#else
std::cout << "not B" << std::endl;
#endif
will print "not B". Is there a way to assign A to another macro variable/function and then wipe out A?
Background: Using this in the context of cmake's configure_file, in which A is defined with a #cmakedefine01.
No.
Macros are not classes and do not have that level of sophistication.
Where one macro is defined in terms of another, both must remain in existence for the substitution to work properly.

#define directives not working outside main() function

I just started learning C++ today. With previous knowledge in other languages I am doing fine so far, but I am confused about #define directives.
I have this code in my "review" C++ file:
#include <iostream>
#define TEST //object-like macro
#ifdef TEST //if TEST is defined
std::cout << "This works!" << std::endl;
#endif
#ifndef NOT_TEST //if NOT_TEST is NOT defined
std::wcout << "This also works!" << std::endl;
#endif
int main()
{
//program code
}
The above code produces errors, first one being syntax error : mssing ';' before '<<'. When I move the #define/#if directives into the main loop, it works properly:
#include <iostream>
int main()
{
#define TEST //object-like macro
#ifdef TEST //if TEST is defined
std::cout << "This works!" << std::endl;
#endif
#ifndef NOT_TEST //if NOT_TEST is NOT defined
std::wcout << "This also works!" << std::endl;
#endif
}
What about the first block of code is incorrect? based on the tutorial I am using, I thought that was how it was supposed to be formatted?
EDIT: I've updated my code to be more clear.
This has nothing to do with formatting. In fact, C++ files are formatting-agnostic. The problem is that after the pre-processor parses your file, you end up with 2 cout statements outside the main function. In C++ you cannot have standalone statements outside of a function, except for declarations/definitions.
You should understand that compilation of a C++ program is a two-step process. First the preproccessor is executed that transforms the file according to instructions you gave it (those that start with #). Then the C++ compiler is executed on the resulting file.
The “code relating to the preprocessor” here is just the #ifdef/#ifndef (with the condition that follows it immediately) and #endif keywords and, indeed, you can put those wherever you like, since preprocessor doesn’t care about C++ syntax, it performs straightforward string operations.
When the preprocessor runs it plugs your C++ code between #ifdef and #endif into the file, so the effect is the same as if you just had the cout << … line (outside the main function).
So, since TEST is defined and NOT_TEST is not, after the preprocessor did its job you are left with a file that has just two lines:
std::cout << "This works!" << std::endl;
std::wcout << "This also works!" << std::endl;
If you try to compile it, you’ll see that the compiler is not happy, because that’s, obviously, not a valid C++ program.
The Problem is using of cout << out of main function.
If you wanna have any output line you can use #error directive to abort compilation process.

How can track execution in C++ without using a debugger?

I have a simple C++ program;
int someFunction()
{
cout << "Testing here" << endl;
cout << "reached here in function " << __LINE__ << " in " << __FUNCTION__ << endl; // debug purposes
// do some more stuffs here
cout << "reached here in function " << __LINE__ << " in " << __FUNCTION__ << endl; // debug purpsoes
}
Is there a way of switching on/off the lines of codes marked as "debug purposes"? The ideas is in case of problems I can just write a one liner to switch on those kind of debug purpose codes and when solved switch them off.
I know debuggers are for this very purpose, but want something simple for simple programs.
You can wrap it in a conditional define:
#ifndef NDEBUG
// Debugcode here
#endif
When you are done debugging, just define NDEBUG during compilation. You might also want to have a look at assert. It is controlled by the same macro NDEBUG and easily lets you check conditions in you program. You can also have it produce meaningful error messages:
assert(allWentWell && "Blah went wrong!");
The error-message of assert will also include information to where the error occurred.
The classical way to solve this is to define some logging macros; a simple example may be:
#ifdef_NDEBUG
# define LOG(X)
#else
# define LOG(X) do { std::clog<<__FILE__<<":"<<__LINE__<<" "<<(X)<<std::endl;} while(0)
#endif
Usage:
LOG("Before frobbing the widget (i="<<i<<")");
Of course this can be taken to any level of complexity (there are quite a few libraries that approach the problem of logging).
In addition of the other replies, you could declare a global flag:
#ifndef NDEBUG
bool want_debug;
#endif /*NDEBUG*/
then define a macro
#ifndef NDEBUG
#define DEBUG_OUT(Expr) do {if (want_debug) \
cout << __FILE__ << ":" << __LINE__ << " " \
<< Expr << endl;} while(0)
#else
#define DEBUG_Out(Expr) do{}while(0)
#endif
and you'll add a lot of statements like
DEBUG_OUT("here x="<< x);
The want_debug flag could be set at runtime (e.g. inside a debugger, or with some -d program argument handled by your main). If you compile with -DNDEBUG you won't get any code for DEBUG_OUT statements.
I'm using the NDEBUG preprocessor symbol related to the old assert(3).
Of course, be careful to avoid meaningful side-effects in DEBUG_OUT, e.g. DEBUG_OUT("here y=" << y++); /*WRONG side effect*/ is certainly a mistake.
If using a recent GCC compiler (e.g. g++ version 4.9), you could also customize it using MELT by adding magically (in your customizing extension coded in MELT) some pass which would automatically add logging messages (e.g. at end of every routine). But that might means weeks of work (so is worthwhile for big existing software projects).
Is you want to "switch on/off" some part of code, you can use macros and preprocessor directives #ifdef and #endif:
#ifdef _DEBUG
//run this code
#endif
Above code will only run, if _DEBUG macro is defined:
#define _DEBUG