Doxygen in C preprocessor if - c

I document my C-Code with Doxygen and got a problem. Consider following example:
in defines.h:
#ifndef DEFINES_H_
#define DEFINES_H_
#define ENABLED 1
#endif
in test.c
#include <defines.h>
/**
* #brief This is the first testfunction
* #return void
*/
void testFunc1(void)
{
//...do stuff
}
#if ENABLED
/**
* #brief This is the second testfunction
* #return void
*/
void testFunc2(void)
{
//...do stuff
}
#endif
Doxygen finds testFunc1 and documents it well, but it cannot find testFunc2. To define ENABLED in the .doxyfile wont fix my problem.
Is there a way to get this running? (Note, I need to define ENABLED inside my c-Project!)

[misread the source snippet]
You probably want #ifdef instead of #if.
From the docs for #if:
The ‘#if’ directive allows you to test the value of an arithmetic expression, rather than the mere existence of one macro.
Its syntax is
#if expression
controlled text
#endif /* expression */
expression is a C expression of integer type, subject to stringent restrictions.
and for #ifdef:
The simplest sort of conditional is
#ifdef MACRO
controlled text
#endif /* MACRO */
This block is called a conditional group. controlled text will be included in the output of the preprocessor if and only if MACRO is defined. We say that the conditional succeeds if MACRO is defined, fails if it is not.

Related

Forward-define a pragma for GCC

I am looking for a solution to forward-declare/define a pragma for GCC.
I use message pragmas as todo list (#pragma message "do this and that").
However, i would like the option to enable/disable the messages completely by a construct as follows:
Warning, this is pseudo-code:
// Definition
#if 1 // generate todo list
#define ADD_TODO(msg) #pragma message "[todo]" msg
#else
#define ADD_TODO(msg) /*empty*/
#endif
// Usage
ADD_TODO("this may result in unitialized variables, fix this")
Has someone experience with such constructs?
You want the _Pragma preprocessing operator (introduced in C99):
// Definition
#define PRAGMA(...) _Pragma(#__VA_ARGS__)
#if 1 // generate todo list
#define ADD_TODO(msg) PRAGMA( message "[todo]" msg)
#else
#define ADD_TODO(msg) /*empty*/
#endif
// Usage
ADD_TODO("this may result in unitialized variables, fix this")
The operator solves the problem of not being able to use preprocessor directives (such as #pragma) inside a #define). It takes a string-literal argument, which is quite impractical to construct by hand, and that is why you'll pretty much always see it wrapped in macro that constructs the string using the # (stringification) operator as shown in the above snippet.

multiple definition error in Clion

I added "Mersenne Twist Pseudorandom Number Generator Package" (one header file and one source file) to my Clion C project, but I can not build the project.
the error is :
multiple definition of `mts_lrand'
I can successfully compile and run the program using just command line and gcc but in Clion i can not.
I think it has something to do with macros, but I do not know how to fix it.
here is some part of the code i added:
mtwist.h
.
.
.
.
/*
* In gcc, inline functions must be declared extern or they'll produce
* assembly code (and thus linking errors). We have to work around
* that difficulty with the MT_EXTERN define.
*/
#ifndef MT_EXTERN
#ifdef __cplusplus
#define MT_EXTERN /* C++ doesn't need static */
#else /* __cplusplus */
#define MT_EXTERN extern /* C (at least gcc) needs extern */
#endif /* __cplusplus */
#endif /* MT_EXTERN */
/*
* Make it possible for mtwist.c to disable the inline keyword. We
* use our own keyword so that we don't interfere with inlining in
* C/C++ header files, above.
*/
#ifndef MT_INLINE
#define MT_INLINE inline /* Compiler has inlining */
#endif /* MT_INLINE */
/*
* Try to guess whether the compiler is one (like gcc) that requires
* inline code to be available in the header file, or a smarter one
* that gets inlines directly from object files. But if we've been
* given the information, trust it.
*/
#ifndef MT_GENERATE_CODE_IN_HEADER
#ifdef __GNUC__
#define MT_GENERATE_CODE_IN_HEADER 1
#endif /* __GNUC__ */
#if defined(__INTEL_COMPILER) || defined(_MSC_VER)
#define MT_GENERATE_CODE_IN_HEADER 0
#endif /* __INTEL_COMPILER || _MSC_VER */
#endif /* MT_GENERATE_CODE_IN_HEADER */
#if MT_GENERATE_CODE_IN_HEADER
/*
* Generate a random number in the range 0 to 2^32-1, inclusive, working
* from a given state vector.
*
* The generator is optimized for speed. The primary optimization is that
* the pseudorandom numbers are generated in batches of MT_STATE_SIZE. This
* saves the cost of a modulus operation in the critical path.
*/
MT_EXTERN MT_INLINE uint32_t mts_lrand(
register mt_state* state) /* State for the PRNG */
{
register uint32_t random_value; /* Pseudorandom value generated */
if (state->stateptr <= 0)
mts_refresh(state);
random_value = state->statevec[--state->stateptr];
MT_PRE_TEMPER(random_value);
return MT_FINAL_TEMPER(random_value);
}
.
.
.
.
you see the function definition is in header file, i think this is the problem but I don't know what to do
you can see complete code here.

How to override assert macro in C?

I want to create my own version of assert in which it does some log prints in case assert was called in NDEBUG mode.
I tried to do the LD_PRELOAD trick and redefine the assert macro but it seems to ignore the macro definition completely and overriding __assert_fail is irrelevant since it isn't called in case of NDEBUG.
How can I override the libc assert macro?
I do not want to create a different function since assert is already used heavily in the project.
Had the same problem using gcc on Cygwin/Windows and on Linux.
My solution is to overwrite the (weak) definition of the actual assertion failed handling function. Here is the code:
/*!
* Overwrite the standard (weak) definition of the assert failed handling function.
*
* These functions are called by the assert() macro and are named differently and
* have different signatures on different systems.
* - On Cygwin/Windows its __assert_func()
* - On Linux its __assert_fail()
*
* - Output format is changed to reflect the gcc error message style
*
* #param filename - the filename where the error happened
* #param line - the line number where the error happened
* #param assert_func - the function name where the error happened
* #param expr - the expression that triggered the failed assert
*/
#if defined( __CYGWIN__ )
void __assert_func( const char *filename, int line, const char *assert_func, const char *expr )
#elif defined( __linux__ )
void __assert_fail ( const char* expr, const char *filename, unsigned int line, const char *assert_func )
#else
# error "Unknown OS! Don't know how to overwrite the assert failed handling function. Follow assert() and adjust!"
#endif
{
// gcc error message style output format:
fprintf( stdout, "%s:%d:4: error: assertion \"%s\" failed in function %s\n",
filename, line, expr, assert_func );
abort();
}
The C99 rationale provides a sample on how to redefine the assert in a good way on page 113:
#undef assert
#ifdef NDEBUG
#define assert(ignore) ((void)0)
#else
extern void __gripe(char *_Expr, char *_File, int _Line, const char *_Func);
#define assert(expr) \
((expr) ? (void)0 :\
__gripe(#expr, _ _FILE_ _,_ _LINE_ _,_ _func_ _))
#endif
I'd include assert.h right before this code to make sure assert.h is used.
Also notice that it calls a function that would do reporting logic, so that your code would be smaller.
It is a pretty simple thing to do, since assert is a macro. Given that you have this code:
#define NDEBUG
#include <assert.h>
int main( void )
{
assert(0);
return 0;
}
Then just do:
#ifdef NDEBUG
#undef assert
#define assert(x) if(!(x)){printf("hello world!");} // whatever code you want here
#endif
Note that this has to be done after #include <assert.h> though.
So if you want to stick your own definition into a common header file, and then use that header file to modify existing code, then your header file have to be included after assert.h.
my_assert.h
#include <assert.h>
#include <stdio.h>
#ifdef NDEBUG
#undef assert
#define assert(x) if(!(x)){printf("hello world!");}
#endif
main.c
#define NDEBUG
#include <assert.h>
#include "my_assert.h"
int main( void )
{
assert(0); // prints "hello world!"
assert(1); // does nothing
return 0;
}
An attempt to try to override the assert() macro in a large codebase can be difficult. For example, suppose you have code like:
#include <assert.h>
#include "my_assert.h"
#include "foo.h" // directly or indirectly includes <assert.h>
After this, any use of assert() will again use the system assert() macro and not the one that you have defined in "my_assert.h" (this is apparently part of the C design of the assert macro).
There are ways to avoid this, but you have to use nasty tricks like putting your own assert.h header in the include path before the system assert.h, which is somewhat error prone and non-portable.
I'd recommend using a different named macro than assert, and use regex tricks or a clang-rewriter to rename the various assert macros in your codebase to an assert macro that you can control. Example:
perl -p -i -e 's/\bassert\b *\( */my_assert( /;' `cat list_of_filenames`
(then adding "my_assert.h" or something like it to each of the files modified)
You can check if NDEBUG is defined and if it is then print whatever logs you want to print.

What does a #define directive without an argument do?

On Apple's opensource website, the entry for stdarg.h contains the following:
#ifndef _STDARG_H
#ifndef _ANSI_STDARG_H_
#ifndef __need___va_list
#define _STDARG_H
#define _ANSI_STDARG_H_
#endif /* not __need___va_list */
#undef __need___va_list
What do the #define statements do if there's nothing following their first argument?
There are sort of three possible "values" for an identifier in the preprocessor:
Undefined: we don't know about this name.
Defined, but empty: we know about this name, but it has no value.
Defined, with value: we know about this name, and it has a value.
The second, defined but empty, is often used for conditional compilation, where the test is simply for the definedness, but not the value, of an identifier:
#ifdef __cplusplus
// here we know we are C++, and we do not care about which version
#endif
#if __cplusplus >= 199711L
// here we know we have a specific version or later
#endif
#ifndef __cplusplus // or #if !defined(__cplusplus)
// here we know we are not C++
#endif
That's an example with a name that if it is defined will have a value. But there are others, like NDEBUG, which are usually defined with no value at all (-DNDEBUG on the compiler command line, usually).
They define a macro which expands to nothing. It's not very useful if you intended it to be used as a macro, but it's very useful when combined with #ifdef and friends—you can, for example, use it to create an include guard, so when you #include a file multiple times, the guarded contents are included only once.
You define something like:
#define _ANSI_STDARG_H_
so that, later you can check for:
#ifdef _ANSI_STDARG_H_

#define IDENTIFIER without a token

What does the following statement mean:
#define FAHAD
I am familiar with the statements like:
#define FAHAD 1
But what does the #define statement without a token signify?
Is it that it is similar to a constant definition?
Defining a constant without a value acts as a flag to the preprocessor, and can be used like so:
#define MY_FLAG
#ifdef MY_FLAG
/* If we defined MY_FLAG, we want this to be compiled */
#else
/* We did not define MY_FLAG, we want this to be compiled instead */
#endif
it means that FAHAD is defined, you can later check if it's defined or not with:
#ifdef FAHAD
//do something
#else
//something else
#endif
Or:
#ifndef FAHAD //if not defined
//do something
#endif
A real life example use is to check if a function or a header is available for your platform, usually a build system will define macros to indicate that some functions or headers exist before actually compiling, for example this checks if signal.h is available:
#ifdef HAVE_SIGNAL_H
# include <signal.h>
#endif/*HAVE_SIGNAL_H*/
This checks if some function is available
#ifdef HAVE_SOME_FUNCTION
//use this function
#else
//else use another one
#endif
Any #define results in replacing the original identifier with the replacement tokens. If there are no replacement tokens, the replacement is empty:
#define DEF_A "some stuff"
#define DEF_B 42
#define DEF_C
printf("%s is %d\n", DEF_A, DEF_B DEF_C);
expands to:
printf("%s is %d\n", "some stuff", 42 );
I put a space between 42 and ) to indicate the "nothing" that DEF_C expanded-to, but in terms of the language at least, the output of the preprocessor is merely a stream of tokens. (Actual compilers generally let you see the preprocessor output. Whether there will be any white-space here depends on the actual preprocessor. For GNU cpp, there is one.)
As in the other answers so far, you can use #ifdef to test whether an identifier has been #defined. You can also write:
#if defined(DEF_C)
for instance. These tests are positive (i.e., the identifier is defined) even if the expansion is empty.
#define FAHAD
this will act like a compiler flag, under which some code can be done.
this will instruct the compiler to compile the code present under this compiler option
#ifdef FAHAD
printf();
#else
/* NA */
#endif

Resources