c++ programming a few useful macro details

  • 2020-05-10 18:36:15
  • OfStack

1. Print error messages

If the execution of the program must require a macro to be defined, you can use #error, #warning to print error (warning) messages when checking that the macro is not defined, such as:


#ifndef __unix__
#error "This section will only work on UNIX systems"
#endif

Only if the macro is defined, can the program be properly compiled.

2. Convenient debugging

S = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s = s

The following statements can be added to the code to track the execution of the code:


if(err) {
printf("%s(%d)-%s\n",__FILE__,__LINE__,__FUNCTION__);
}
 

3. Mixed programming of C/C++

Function int foo(int a, int b);

In C, the function is compiled by the compiler and is called _foo in the library, while in C++, the function is compiled and named _foo_int_int in the library (a change to implement function overloading). If a library function compiled by C is required for C++, the function cannot be found because the symbol name does not match. C++ USES extern "C" to solve this problem, indicating that the function to be referenced is compiled by C and should be named according to C.

If foo is a library compiled by C, if foo is to be used in C++, declare that this is a macro predefined by c++ compiler, indicating that this file is compiled by C++ compiler.


#ifdef __cplusplus
extern  " C "  {
#endif
   extern int foo(int a, int b);
 
#ifdef __cplusplus
}
#endif
 

4. Variable parameters

#define debug(format, args...) fprintf (stderr, format, args)
#define debug(format, ...) fprintf (stderr, format, __VA_ARGS__)

Or #define debug(format,...) S 73en (stderr, format, ## s 76en_ARGS__)

The first two have the problem of redundant commas, and the third macro USES ## to remove any possible redundant commas.


Related articles: