#define cimg_use_jpeg 2
#ifndef cimg_use_jpeg
//code goes here
#endif
I really don't understand...
Every time things similar to this (so-called impossible things) happen me, the reason is: The code I see in my editor is not the code that runs. This can happen in many ways.
forgetting to make
forgetting to save
saving a copy of the code
running in a different evironment from the one you compiled to
the new code ran but I opened and am looking at the old output
It cannot be executed. Maybe you run incorrect executable version. Printing __DATE__ and __TIME__ to trace or log helps to detect such errors.
This should definately work as you expect. The code in the #ifndef/#endif block will not even be compiled by the compiler, assuming the cimg_use_jpeg is defined as expected.
So the question is, is the cimg_use_jpeg defined as you expect? Or are you simplifying your question and by virtue of the simplification providing a sample that actually works?
#Anders K. This works, i.e. the proper things are not executed. The code produces "BAZ is undefined"
#define FOO 2
#define BAR
int main(int argc, char* argv[])
{
#ifndef FOO
std::cout << "FOO is undefined" << std::endl;
#endif
#ifndef BAR
std::cout << "BAR is undefined" << std::endl;
#endif
#ifndef BAZ
std::cout << "BAZ is undefined" << std::endl;
#endif
}
Either you write
#define yoursymbol
#ifdef yoursymbol
or you write
#define yoursymbol somevalue
#if yousymbol == somevalue
don't mix them
EDIT:
since people seem to misunderstand what I meant here's a clarification: when you program it is important to code so that other people understand what your intentions are, so if your intention is only to check whether a symbol is defined it is confusing to specify a numerical value.
Related
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
Below is an example of using a debug variable
class A{
public:
A(bool debug):m_debug(debug){};
~A(){};
void Test(){
for(int i=0;i<1000000;i++){
// do something
if(m_debug) print();
}
}
void print(){
std::cout << "something" << std::endl;
}
private:
bool m_debug;
};
Below is an example of using a debug macro preprocessor
#include "Preprocessor.h"
class A{
public:
void Test(){
for(int i=0;i<1000000;i++){
// do something
#ifdef DEBUG
print();
#endif
}
}
void print(){
std::cout << "something" << std::endl;
}
};
In Preprocessor.h is simply
#define DEBUG
The good thing about using a debug variable is the class has one less dependency on a global preprocessor header. The good thing about the macro approach is that there are 1000000 less if statement executed at run time, which might be critical for lets say graphics application when every single fps counts. What would be considered as a better approach?
The better approach is to use preprocessor, however, it do not necessary a new header file to define the macro.
You can set the flag at compiling, using -DMACRO_NAME or, in your case, -DDEBUG.
As long as the job is printing debug info, the precedent is to use macros like Visual Studio does (debug/release build). However in Qt world, there is class QLoggingCatagory where you can enable/disable logging sections. It calls the function QLoggingCategory::isDebugEnabled()every time a message is being logged out which makes me think it is not a major issue for performance at least for normal use.
That said if we comapare Visual Studio MFC application with Qt application, MFC applications are lighting fast. This could be attributed at least in part because it uses macros and the difference can be noticed rather easily in debug and release build as well where macro/debug info is the main difference.
Given all this evidence my vote is for macros approach in your case for maximum performance.
First, the macro way is better for both benefits in memory and if testing(though this is really minor cost). Do you have any special scenarios to use the debug variable?
why not define the A::Test() in the CPP file? thus the global preprocessor header could be moved to the CPP file. Anyway, I don't think expose such debug details in the header is a good idea.
Another alternative, if you do not like having a bunch of #ifdef DEBUG / #endif lines, you could create a macro that outputs it's argument if defined (much like the assert macro).
#ifdef DEBUG
#define PRINT(x) (x)
#else
#define PRINT(x)
#endif
PRINT( std::cout << "something" << std::endl );
The code path does not get much more minimal than "compiled away". However, if you are willing to perform a refactoring step, you can make the run-time debug version cheaper at the cost of a larger executable.
The idea is to make the debug state a template parameter of a refactored version of Test() so that it may or may not print a debug statement on each iteration. The compiler's dead code elimination pass will then optimize away the statement in the case false is passed to the template, since template parameters will be treated as compile time constants in the template expansion.
The fully optimized version can still use conditional compilation to always disable debug output, of course.
template <bool Debug>
void TestDebug(){
for(int i=0;i<1000000;i++){
// do something
if (Debug) print();
}
}
void Test(){
#ifdef DEBUG
if(m_debug) TestDebug<true>();
else TestDebug<false>();
#else
TestDebug<false>();
#endif
}
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.
This isn't a typical question to solve a specific problem, it's rather a brain exercise, but I wonder if anyone has a solution.
In development we often need to disable or switch some parts of code to check different approaches. To do this we use comments or #defines, but my favorite is:
//*
[code here]
//*/
Now when you remove just the first slash the code will become commented-out.
The question: is there any way to implement similar if-else code switch? I tried to find it but I always had some problem and couldn't find a working solution.
And maybe do you know any similar tricks?
Wrapping the code with #if 0 does the trick but then you still need to edit the code to enable/disable it. That's not much better than just using the comment block.
Note that you can also use a defined preprocessor constant:
#ifdef ENABLE_TESTS
// code that you want to run ONLY during tests
#endif
Now when building the code, you can selectively define/un-define this constant in your build process - IDE/makefile/build script/command-line - without needing to edit the code:
$ gcc -DENABLE_TESTS source.c
I've added this answer to counter-balance all of the early #if 0 answers, but this construct from the accepted answer is the best answer to the specific question: /**/ foo(); /*/ bar(); /**/. Please use such comment tricks sparingly.
#if 0
...disabled code here
#endif
I'm not sure I should post this because it's not something I think is 'good code', but I'll admit to having used the following technique as a quick-n-dirty way to be able to quickly switch between two small snippets of code when I'm just checking something out:
// in the following , foo() is active:
/**/ foo(); /*/ bar(); /**/
Now just remove one of the asterisks at the front:
// now bar() is active:
/*/ foo(); /*/ bar(); /**/
Of course, this should never make it past the "just checking things out" phase...
Preprocessor if-else also works
#if 1
// ... enabled if 1
#else
// ... enabled if 0
#endif
Use some preprocessor logic to help you out here:
#if 0
//code goes here
#endif
Enjoy
Sometimes I use the below trick to switch between two lazy comments.
//* <-- remove the first slash
[code block 1]
/*/
[code block 2]
//*/
Well, if the code that needed to be disabled once or twice before finalizing, I prefer to use hotkeys provided by IDE to comment that code out, and later comment in. Yes, I need to select the code block first, but I prefer not to include one more debugging variable/preprocessor directive/if statement every time I need to disable a part of code. This happens to be most of the time.
If, on the other hand, I need to repeatedly switch between 2 code blocks to find the right thing, then I use a if (0) / if (1) to disable/enable code block.
[code block 1]
Later
if (0)
{
[code block 1]
}
else
{
[code block 2]
}
If you're doing checks at compile time, you can use Gigi's answer, which will conditionally not compile sections of code. Note that the preprocessor has no knowledge of variables, or sizeof, or other things handled by the compiler (so using something like 4 == sizeof(int) will not fly)
If you want to compile in little bits of debugging code that should not ever get run, you can use regular conditional statements, like such
bool debugging = false;
// banana banana banana
if (debugging)
{
// do a bunch of stuff here
}
You can then use a debugger to access the skipped section by assigning debugging to true.
Macro is the way to do this..
#define COMPILE
#ifdef COMPILE
//code to comment begins
cout<<"ha ha ha"<<endl;
//code to comment ends
#endif
To disable the code, just comment out #define compile line
Synchronously switching on/off chunks of code scattered across the program is sometimes a need too.
Inspired by this earlier post by Graham I cooked up something like this:
void doNothing(){}
#define DO_IF(flag, code) flag ? code : doNothing();
This can be for instance used as follows:
DO_IF(collectStats, recordStats());
DO_IF(collectStats, store(pullStat()));
An that is even better:
#define DO_IF(flag,code) if( flag ) { code; }
1 ? foo() : bar();
This executes foo(). Change the 1 to a 0 to execute bar() instead.
Unlike the suggestions involving preprocessor directives or comments, both possible branches are compiled, so you get the full benefit of the compiler's syntax checking.
Sometimes i use this approach to just not overbloat the code by infinite sequence of if-endif definitions.
debug.hpp
#ifdef _DEBUG
#define IF_DEBUG(x) if(x)
#else
#define IF_DEBUG(x) if(false)
#endif
example.cpp
#include "debug.hpp"
int a,b, ... ,z;
...
IF_DEBUG(... regular_expression_here_with_a_b_z ...) {
// set of asserts
assert(... a ...);
assert(... b ...);
...
assert(... z ...);
}
This is not always effective, because compiler may warn you about unused variables has used inside such disabled blocks of code. But at least it is better readable and unused variable warnings can be suppressed for example like this:
IF_DEBUG(... regular_expression_here_with_a_b_z ...) {
// set of asserts
assert(... a ...);
assert(... b ...);
...
assert(... z ...);
}
else {
(void)a;
(void)b;
....
(void)z;
}
It is not always a good idea, but at least helps to reorganize the code.
the following logic should contain the simplest approach
if(isMode1)
{
//Code for mode1
}
else
{
//Code for other modes
}
although I think the correct way is to use PreProcessor Directives
In my code, I like to do this in my main.cpp file:
#define CRAZY_EXPERIMENT
#ifdef TEST
#include "Test.h"
#elif ANOTHER_TEST
#include "AnotherTest.h"
#elif CRAZY_EXPERIMENT
#include "CrazyExperiment.h"
#else
int main(int argc, int * argv[]){
runTheProgramLikeNormal();
}
#endif
The header files you see all contain their own main(). There is only ever one main() function in the program based on what is defined in the first #define there. If the statement is omitted entirely, it defaults to the canonical main() function you see written.
This makes it easy to write tests for my program that only focus on one or two components by themselves. And the best part is that the test headers are neatly quarantined from my code, so no test code gets left in (or even linked in) by mistake.
I have the following bit of code, I expect that given cstdio is included that the first line will be printed, however the second line is printed.
What am I doing wrong? is it possible to know if labels such as printf or strncmp or memcpy have been defined in the current translation unit at compile time?
#include <iostream>
#include <cstdio>
int main()
{
#ifdef printf
std::cout << "printf is defined.\n";
#else
std::cout << "printf NOT defined!\n";
#endif
return 0;
}
Is the reason because the preprocessor is run before variables and labels are introduced into the scope/TU?
In short is the following code bogus? :
http://code.google.com/p/cmockery/source/browse/trunk/src/example/calculator.c#35
#ifdef only applies to preprocessor macros, defined with #define, not to symbols like function names and variables. You can imagine the preprocessor as an actual separate preliminary step, like running your code through a perl script, that occurs before the "real" compiler gets a crack at it.
So there is no programmatic way to check whether symbols like printf are defined in the current scope. If you use one and it's not defined, you'll get a compiler error. The normal thing to do is to #include a header file with the required definition in the source file where you reference it, not to write a source file that will adapt itself to different possible sets of headers.
As a hack, and depending on your environment and specific problem, the header file that does define printf (or whatever function you care about) may also contain some preprocessor #defines that you could check for.
You can use the guards from original include files to determine if they were included and, consequently, functions were declared.
For example, <stdio.h> shipped with my MSVS2010 has _INC_STDIO guards. Thus your code should be like:
int main()
{
#ifdef _INC_STDIO
std::cout << "printf is defined.\n";
#else
std::cout << "printf NOT defined!\n";
#endif
return 0;
}
Note that this solution is environment-dependent, so you should create more complicated rules it you are supposed to support more than one build chain.
Their are a large number of symbols in stdio.h which are #defined, and it is imported by cstdio
So you could use
#include <iostream>
#include <cstdio>
int main()
{
#ifdef stdin
std::cout << "printf is defined.\n";
#else
std::cout << "printf NOT defined!\n";
#endif
return 0;
}
WARNING I've looked at the header but not tested.