I need a macro to expand to a c++ comment, is that possible?
I've got this:
#define SLASH(x,y) x y
#define OUT SLASH(/,/)
int main(int argc, char *argv[])
{
OUT << "text";
return 0;
}
And need to expand to this:
{
// << "text";
return 0;
}
I've also tried this:
#define SLASH(x) /x
#define OUT SLASH(/)
But the result is still the same:
int main(int argc, char *argv[])
{
/ / << "text";
return 0;
}
No it's not possible because in C++ comments are removed before macros are expanded.
(See 2.1 of the standard, comment removal happens in phase 3, macro expansion in phase 4.)
What about replacing it with a function object that does nothing instead?
static class NullOutput {
public:
template <typename T>
const NullOutput &operator<<(T arg) const {
return *this;
}
} NullOutputObj;
#define OUT NullOutputObj
The net result is that the object is removed from the code and replaced by inlined template expansions, that are then optimized out as they do nothing. Result is absolutely no code overhead.
As others mentioned there is no guaranteed way to define the kind of macro you are looking for. Other ways to achieve results that are similar to what you seem to be trying to achieve are wrapping your output statement in a conditional block or define a custom output stream that just discarded all output. The two approaches may even be combined so that behaviour could be switched by changing a single macro definition.
Comments are removed from the source code before the preprocessor runs. So you cannot do this.
an alternate to what you want to achieve would be this :
http://donjaffer.blogspot.in/2012/09/dprintf-debug-macro-in-c.html
#define DEBUG // comment if you do not want the debug statments to appear.
#ifdef DEBUG
#define DPRINTF(fmt, ...) \
do { printf("my_file: " fmt, ## __VA_ARGS__); } while (0)
#else
#define DPRINTF(fmt, ...) \
do { } while (0)
#endif
wherever you are trying to print the statements, instead of COUT << you can use
DPRINTF("Your text here\n");
Related
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
I'm trying to create a macro for debug logging purposes. Here is an extra simplified version:
#if defined _DEBUG
#define LOG std::cout
#else
#define LOG IGNORETHISLINEOFCODE
#endif
/* ... */
LOG << "Here's some debug code";
I've been thinking of the ways I can tell the compiler to ignore this line of code that starts with "LOG". I'm personally not looking for alternative ways, such as #define LOG( ... ) (void)0. Here's what I've tried:
Overloading the leftshift operator for void as an inline constexpr that does nothing (which still results in it being visible in the disassembly; I don't want that)
Defining LOG as: #define LOG //, but the comment identifier isn't substituted in
Any ideas? Like I said earlier, I don't want any alternatives, such as surrounding all the log code with #if defined _DEBUG
If your version of C++ handles if constexpr I've come to like things along this line for what you're asking.
#include <iostream>
template <bool Log>
struct LOGGER {
template <typename T>
LOGGER& operator<<(T const &t) {
if constexpr (Log)
std::cout << t;
return *this;
}
};
LOGGER<false> LOG;
int main (int argc, char const* argv[])
{
LOG << "A log statement." << '\n';
return 0;
}
Your question and constraint ("I don't want any alternatives") are weirdly specific.
I've been thinking of the ways I can tell the compiler to ignore this line of code that starts with "LOG"
Don't do that, it'll be trivially broken by a multi-line logging statement. Any code that can suddenly break due to otherwise-legal reformatting is best avoided.
Next we have
... which still results in it being visible in the disassembly ...
which shouldn't be true if the code is genuinely dead, you have a decent compiler, and you turn on optimization. It's still some work, though.
The usual solution is something like
#ifdef NDEBUG
#define LOG(EXPR)
#else
#define LOG(EXPR) std::cerr << EXPR
#endif
This is an alternative, but it's not an alternative such as surrounding all the log code with #if defined, so I don't know if it's a problem for you or not.
It does have the advantage of genuinely compiling to nothing at any optimization level.
another possibility based on the compiler optimization abilities:
#define LOG if (DEBUG) std::cout
now you can use
#define DEBUG false
LOG << "hello " << " world 1" << endl;
you should be able to use const bool DEBUG = false as well.
#if defined _DEBUG
#define LOG std::cout
#else
#define LOG /##/
#endif
This works as well. It's the answer to the original question, so I'll mark it as such, but just know that this does not support multiline operations.
I suppose you could do something like the following for multiline operations. I don't know how well it'd work.
#if defined _DEBUG
#define LOG( in ) std::cout << in
#else
#define LOG( in ) /##/
#endif
Better logic would be to define tracer policy, where you can set the logging level at the start of the application and then use the tracing level to make the decision to either log the degug information. Tracing level can be defined as an enum like
enum Tracelevel{CRITICAL, ERROR, INFO, TEST, DEBUG};
setTraceLevel(TraceLevel trcLvl){
_traceLevel = trcLvl;
};
#if defined _DEBUG
if(_traceLevel == DEBUG) {\
#define LOG std::cout
}
#endif
A lightweight logger can be found http://www.drdobbs.com/cpp/a-lightweight-logger-for-c/240147505?pgno=1
My application uses another output than the standard output for logging information, which is why I wrote my own Log(), Error(), Panic() and Assert() functions. To organize things nicely, I enclose all the debugging stuff in a Debug namespace.
It would make more sense for the Assert() function to also provide a source file and line number, which is only possible using the __LINE__ and __FILE__ macros. However, it is pretty unpleasant, inefficient etc... to always have to specify these two parameters.
So this is how my code would look like:
namespace Debug {
void Assert (int condition, std::string message, std::string file, int line);
}
My question is, is it possible to place a macro which includes those two parameters inside the Debug namespace? Like this:
namespace Debug {
void Assert_ (int condition, std::string message, std::string file, int line);
#define Assert(a,b) Assert_(a, b, __FILE__, __LINE__)
}
// .... Somewhere where I call the function ....
Debug::Assert (some_condition, "Some_condition should be true");
// Output: Assertion failed on line 10 in file test.cpp:
// Some_condition should be true
Is this valid c++? If not, is there any way of making this work?
#define is a preprocessor directive. The macros are being replaced before anything else apart from removing comments (which means, before compilation). So at the time macros are replaced, the compiler knows nothing about your namespaces.
As other people state, in your case it will be fine. However, This is how you can get problems:
namespace A
{
void Assert_ (int condition, std::string message, std::string file, int line)
{
std::cout << "A";
}
#define Assert(a,b) Assert_(a, b, __FILE__, __LINE__)
}
namespace B
{
void Assert_ (int condition)
{
std::cout << "B";
}
#define Assert(a,b) Assert_(a)
}
int main(int argc, char *argv[])
{
A::Assert(0,"asdasd");
B::Assert(0,"asdasd");
}
So while it looks like the defines are "in the namespaces", they are not, and the last #define will be always be used, which in this case will lead to a compile-time error, because the code in main will be replaced by:
A::Assert(0);
B::Assert(0);
instead of
A::Assert(0,"asdasd", _FILE_, _LINE_);
B::Assert(0);
No, the preprocessor doesn't care about namespaces at all. In fact, the preprocessor runs, at least conceptually, before the compiler sees anything.
For myself, I just do a standard ASSERT macro, and expect that no "sane namespace" has something called ASSERT. Problem solved. Should I require a library that has an ASSERT of its own then I can still decide how to deal with this; however, the only library that I'm currently using with its own "assert" calls it BOOST_ASSERT or something like that...
namespace Debug
{
void Assert_(int condition, std::string message, std::string file, int line);
#define Assert(a,b) Assert_(a, b, __FILE__, __LINE__)
}
// .... Somewhere where I call the function ....
Debug::Assert (some_condition, "Some_condition should be true");
This specific usage would do exactly what you want, but the Assert macro is in no way part of the Debug namespace... it's exactly as if you'd done:
namespace Debug
{
void Assert_(int condition, std::string message, std::string file, int line);
}
#define Assert(a,b) Assert_(a, b, __FILE__, __LINE__)
// .... Somewhere where I call the function ....
Debug::Assert (some_condition, "Some_condition should be true");
Here, the substitution works not because Assert was in the Debug namespace (it's not in your code or this code, and the preprocessor has no clue what namespaces are about) - it works because Assert is recognised as an identifier for a macro, the substitution of Assert_ is made, then later the compiler proper happens to find there's a Debug::Assert_
So, say you have somewhere later in your translation unit you have some completely unrelated code:
my_object.Assert(my_functor);
The macro substituion will still kick in to produce a compile-time error saying you have the wrong number of arguments to a macro. Say the unrelated code was instead:
my_object.Assert(my_functor, "some text");
Then that would be replaced with:
my_object.Assert_(my_functor, "some text", __FILE__, __LINE__);
(Separately, it's standard practice not to use lower case letters in preprocessor macro names).
You can try __PRETTY_FUNCTION __ macro to print all the namespaces including function arguments.
Yes, and your macro would expand to exactly what you expect.
Debug::Assert (some_condition, "Some_condition should be true");
would be replaced by
Debug::Assert_(some_condition, "Some_condition should be true", __FILE__, __LINE__)
I came across this line of code in legacy code:
#define func(x,y) if(strcmp(x,#y)==0)
Anyone have an idea of the purpose for the # symbol preceding y?
as mentioned in the comments, this seems like stringification in a c macro.
here is a little example that uses your sample code:
#define doif(x, y) \
if(strcmp(x,#y)==0) { \
printf("doing! %s\n",x); \
}\
else { \
printf("not doing!\n"); \
}
int main()
{
char x[] = "test";
doif (x, test);
doif (x, something);
return 0;
}
the stringification operator actually pastes y variable as a string before the compilation stage
First of all you posted wrong or in complete code. #y should be used with macro definition, not while using macro.
#define MAC(STR) #STR
int main(int argc, char* argv[])
{
printf(MAC(ME));//prints ME
printf(MAC("ME"));//prints "ME"
return 0;
}
Here I have defined MAC macro which takes one argument. I did it's stringification.
Also see second printf, it exactly prints string. So you need not to give pair of "".
I wrote a logging mechanism with several log levels.
LOG_FATAL(s)
LOG_ERROR(s)
LOG_WARN(s)
...
Now I want to be able to activate or deactivate the logging for some modules.
What I do now:
#ifdef MOUDLE_LOG_ON
MODULE_LOG_FATAL(s) LOG_FATAL(s)
MODULE_LOG_ERROR(s) LOG_ERROR(s)
MODULE_LOG_WARN(s) LOG_WARN(s)
...
#else
MODULE_LOG_FATAL(s)
MODULE_LOG_ERROR(s)
MODULE_LOG_WARN(s)
...
#endif
Is there a way to place the prefixing in a macro to use it like this:
SETUPLOGGING(MODULE)
I am wondering if using macros and inline functions could solve your issue:
void inline LOG_FATAL(const char *s)
{
printf("%s\n", s);
}
#define SETUPLOGGING(x) \
void inline x ## _LOG_FATAL(const char *s) { LOG_FATAL(s); }
SETUPLOGGING(MODULE)
int main()
{
MODULE_LOG_FATAL("hello");
}
After preprocessing, this produces:
void inline LOG_FATAL(const char *s)
{
printf("%s\n", s);
}
void inline MODULE_LOG_FATAL(const char *s) { LOG_FATAL(s); }
int main()
{
MODULE_LOG_FATAL("hello");
}
Macros can't define new macros. And when defining a macro, it isn't possible to build its name from other macro, so you can't use the common work around of including a file which defines what you want.
You could use a macro to define which include file you were going to use, but then, why not use an include file and use the macro in there?