C: `Turn on debug messages - c

This is probably a really stupid question, but how do I turn on these debug messages in my code?
#ifdef DEBUG_MSG
printf("initial state : %d\n", initial_state);
#endif
Many thanks in advance,

When compiling, try something like this:
$ gcc -DDEBUG_MSG -o foo foo.c

You would have to #define that somehow.
0. In your code.
Directly in your code somewhere before you use that flag:
#define DEBUG_MSG
1. On the command line.
For each sourcefile, or appropriately in your makefile:
gcc -DDEBUG_MSG main.c
(For gcc, the flag is -D<macro-name>, for MSVC, it is /D, for ICC it is one of the former, depending on your operating system. )
2. In your IDE, somewhere.
In your IDE's project settings, find where you can put definitions. Under the hood, this is done using 1.

#ifdef means 'If defined', your code essentially tells the preprocessor to check if DEBUG_MSG is defined somewhere else. If it is, it will include the code you've shown.

The C preprocessor phase will only pass code inside an #ifdef/#endif to the compiler phase if the symbol is defined.
You can generally do this in (at least) two ways.
The first is to use a command line switch for the compiler such as:
gcc -DDEBUG_MSG myprog.c
(-D means to define the pre-processor symbol following it and, although this is implementation-specific, many compilers use the same switch). The second is to place a line like:
#define DEBUG_MSG
inside your actual source code somewhere before the #ifdef.
The former is usually preferred since it allows you to control that behaviour without having to make changes to your source code so that, for example, you can have a debug and release build generated from the same source code.

#ifdef will make your macro to be expanded only if DEBUG_MSG is defined. You can do this in two ways. Either do a #define DEBUG_MSG 1 in your source or compile using -DDEBUG_MSG (if using gcc, there are similar flags for other compilers too)

Related

How to check macros defined in .so? I'd use nm to check the function, is there a way to do the same for macros?

I have a code like this in mylib.h, and then I use it to create mylib.so.
Is there a way to check how MY_MACROS is defined in .so?
#ifdef SWITCH_CONDITION
#define MY_MACROS 0
#else
#define MY_MACROS 1
#endif
If that would be a function, I'd simply do
nm mylib.so | grep myfunction
Is there a way to do the same for macros?
P.S. There should be because of
> grep MY_MACROS mylib.so
> Binary file mylib.so matches
In general there is no way to do this sort of thing for macros. (But see more below.)
Preprocessor macros are theoretically a compile-time concept. In fact, in the early implementations of C, the preprocessor was -- literally -- a separate program, running in a separate process, converting C code with #include and #define and #ifdef into C code without them. The actual C compiler saw only the "preprocessed" code.
Now, theoretically a compiler could somehow save away some record of macro definitions, perhaps to aid in debugging. I wasn't aware of any that did this, although evidently those using the DWARF format actually do! See comments below, and this answer.
You can always write your own, explicit code to track the definition of certain macros. For example, I've often written code elong the lines of
void print_version()
{
printf("myprogram version %s", VERSION_STRING);
#ifdef DEBUG
printf(" (debug version)");
#endif
printf("\n");
}
Some projects have rather elaborate mechanisms to keep track of the compilation switches which are in effect for a particular build. For example, in projects managed by a configure script, there's often a single file config.status containing one single record of all the compilation options, for posterity.
Yes, but it requires debugging info.
You can compile your code with -g3:
$ gcc -g3 -shared -fPIC test.c -o test.so
and then run strings on the resulting binary:
$ strings test.so
...
__DEC32_EPSILON__ 1E-6DF
MY_MACROS 1
__UINT_LEAST32_TYPE__ unsigned int

Cpp : How to understand and/or debug complex macros?

I am trying to learn preprocessor tricks that I found not so easy (Can we have recursive macros?, Is there a way to use C++ preprocessor stringification on variadic macro arguments?, C++ preprocessor __VA_ARGS__ number of arguments, Variadic macro trick, ...). I know the -E option to see the result of the preprocessor whole pass but I would like to know, if options or means exist to see the result step by step. Indeed, sometimes it is difficult to follow what happens when a macro calls a macro that calls a macro ... with the mechanism of disabling context, painting blue ... In brief, I wonder if a sort of preprocessor debugger with breakpoints and other tools exists.
(Do not answer that this use of preprocessor directives is dangerous, ugly, horrible, not good practices in C, produces unreadable code ... I am aware of that and it is not the question).
Yes, this tool exists as a feature of Eclipse IDE. I think the default way to access the feature is to hover over a macro you want to see expanded (this will show the full expansion) and then press F2 on your keyboard (a popup appears that allows you to step through each expansion).
When I used this tool to learn more about macros it was very helpful. With just a little practice, you won't need it anymore.
In case anyone is confused about how to use this feature, I found a tutorial on the Eclipse documentation here.
This answer to another question is relevant.
When you do weird preprocessor tricks (which are legitimate) it is useful to ask the compiler to generate the preprocessed form (e.g. with gcc -C -E if using GCC) and look into that preprocessed form.
In practice, for a source file foo.c it makes (sometimes) sense to get its preprocessed form foo.i with gcc -C -E foo.c > foo.i and look into that foo.i.
Sometimes, it even makes sense to get that foo.i without line information. The trick here (removing line information contained in lines starting with #) would be to do:
gcc -C -E foo.c | grep -v '^#' > foo.i
Then you could indent foo.i and compile it, e.g. with gcc -Wall -c foo.i; you'll get error locations in the preprocessed file and you could understand how you got that and go back to your preprocessor macros (or their invocations).
Remember that the C preprocessor is mostly a textual transformation working at the file level. It is not possible to macro-expand a few lines in isolation (because prior lines might have played with #if combined with #define -perhaps in prior #include-d files- or preprocessor options such as -DNDEBUG passed to gcc or g++). On Linux see also feature_test_macros(7)
A known example of expansion which works differently when compiled with or without -DNDEBUG passed to the compiler is assert. The meaning of assert(i++ > 0) (a very wrong thing to code) depends on it and illustrates that macro-expansion cannot be done locally (and you might imagine some prior header having #define NDEBUG 1 even if of course it is poor taste).
Another example (very common actually) where the macro expansion is context dependent is any macro using __LINE__ or __COUNTER__
...
NB. You don't need Eclipse for all that, just a good enough source code editor (my preference is emacs but that is a matter of taste): for the preprocessing task you can use your compiler.
The only way to see what is wrong with your macro is to add the option which will keep the temporary files when compilation completes. For gcc it is -save-temps option. You can open the .i file and the the expanded macros.
IDE indexers (like Eclipse) will not help too much. They will not expand (as other answer states) the macros until the error occures.

How to know if a flag used by preprocessor (like #ifdef or #if) is indeed defined or not

I was diving into the glibc source code and found quite a lot of usages of preprocessors like
#ifdef XXX
and
#if YYY
In order to know the exact behavior of the glibc that will be compiled and run on my machine, I have to know whether these flags are indeed defined or not. What I am currently doing is to insert the following piece of code to somewhere, compile, and run, which is neither elegant nor efficient.
#ifdef XXX
printf("XXX defined");
#endif
Anther way might be to grep the flag in the entire source tree, but I found this way not very reliable. Because sometimes I didn't find any #define XXX but I still got XXX defined printed out. (Can anyone let me know why?)
Therefore, I want to know what is the best practice to do this.
I found that combination of gcc with -g3 and gdb is pretty useful for checking macros and even macro-expansions for function-like macros. See man gcc and 12 C Preprocessor Macros from GDB manual for more details.
As more "invasive" way you could put #pragma message (or some similar) directive to examine individual macros during compilation:
Prints string as a compiler message on compilation. The message is
informational only, and is neither a compilation warning nor an error.
There is also -E switch, that allows to simply look into preprocessed translation unit.

Macros giving problems with dladdr()

I have implemented tracing behavior using the -finstrument-functions option of gcc and this (simplified) code:
void __cyg_profile_func_enter(void *this_fn, void *call_site)
{
Dl_info di;
if(dladdr(this_fn, &di))
printf("entered %s\n", (di.dli_sname?di_dli_sname:"<unknown>"));
}
This works great, except for one thing: macros are processed as well, but the function prints the information of the function which contains the macro.
So functions containing macros have their information printed multiple times (which is of course undesired).
Is there anything to detect that a macro is being processed? Or is is possible to turn off instrumenting macros at all?
PS Same problems occur with sizeof()
Edit: To clarify: I am looking for a solution to prevent macros messing with the instrumented functions (which they should not be doing). Not for methods to trace macros, functions and/or other things.
Macros are expanded inline by the preprocessor, therefore there is no way to distinguish between a function called directly from the code and called from a macro.
The only possible way around this would be to have your macros set a global flag, which your tracing function will check.
This is of course less than foolproof, since any calls done by a function called from a macro will also appear the same way.
If you really want to dig into it you can see my response to breakdown c++ code size. C++ templates are really just more formal macros, so this may work for you.
It also may not, since LINE and FILE within a macro correspond to the caller.
edit
from my comment on this:
$ gcc -E foo.c | gcc -x c-cpp-output -c -finstrument-functions - -o foo.o
preprocess piped into gcc expecting preprocessed input on standard input

Check whether function is declared with C preprocessor?

Is it possible to tell the C preprocessor to check whether a function (not a macro) is declared? I tried the following, but it doesn't appear to work:
#include <stdio.h>
int main(void)
{
#if defined(printf)
printf("You support printf!\n");
#else
puts("Either you don't support printf, or this test doesn't work.");
#endif
return 0;
}
No. Preprocessor runs before the C compiler and the C compiler processes function declarations. The preprocessor is only there for text processing.
However, most header files have include guard macros like _STDIO_H_ that you can test for in the preprocessor stage. However, that solution is not portable as the include guard macro names are not standardized.
If you look at tools like autoconf you will see that they go through many tests to determine what a computer has or doesn't have, to compile properly, then they set the correct #DEFINES.
You may want to look at that model, and that tool if you are on some flavor of unix, as what you want to do isn't going to be possible, as others undoubtedly are pointing out.
Strictly speaking no, the preprocessor can't do it on its own. However, you can give it a little help by creating appropriate #defines automatically.
Normally as was mentioned above, you'd use autotools if on a unix type system. However, you can also create the same effect using a makefile. I recently had cause to detect the "posix_fallocate" function being defined in headers, because I was using uClibc which seemed to omit it in earlier versions. This works in gnu make, but you can probably get a similar thing to work in other versions:
NOFALLOC := $(shell echo "\#include <fcntl.h>\nint main() { posix_fallocate(0,0,0);}" | $(CC) -o /dev/null -Werror -xc - >/dev/null 2>/dev/null && echo 0 || echo 1)
ifeq "$(NOFALLOC)" "1"
DFLAGS += -DNO_POSIX_FALLOCATE
endif
The preprocessor is a simple program and knows next to nothing about the underlying language. It cannot tell if a function has been declared. Even if it could, the function may be defined in another library and the symbol is resolved during linking, so the preprocessor could not help in that regard.
Since the preprocessor is not aware of the language C/C++ (it really only does text-replacement) I would guess that this is not possible. Why do you want to do this? Maybe there is another way.

Resources