clang-format: indentation of macros - c++

I am trying to apply clang-format to an existing code base and came across the following issue:
Simplified (and formatted) sample code:
#define QUERY_BEGIN()
#define QUERY_NORESULT()
#define QUERY_END()
void foo()
{
int a = 0;
QUERY_BEGIN()
a = 1;
QUERY_NORESULT()
a = 2;
QUERY_END()
}
I set the following options:
MacroBlockEnd: 'QUERY_END'
MacroBlockBegin: 'QUERY_BEGIN'
What I want to achieve is the following formatting of the macro part:
QUERY_BEGIN()
a = 1;
QUERY_NORESULT()
a = 2;
QUERY_END()
My first guess was to set QUERY_NORESULT as MacroBlockEnd and MacroBlockBegin but that didn't help. It results in the following formatting:
QUERY_BEGIN()
a = 1;
QUERY_NORESULT
a = 2;
QUERY_END()
Is there currently a way to achieve the indentation as shown above?

Bad news: Sorry, this is not available in the current release version of clang-format(7).
Good news: There is a StatementMacros option, which is available since clang-format 8(not release yet, but you can build from source).
See this commit:
Summary:
Some macros are used in the body of function, and actually contain the trailing semicolon: they should thus be automatically followed by a new line, and not get merged with the next line. This is for example the case with Qt's Q_UNUSED macro:
void foo(int a, int b) {
Q_UNUSED(a)
return b;
}
This patch deals with these cases by introducing a new option to specify list of statement macros. This re-uses the system already in place for foreach macros, to ensure there is no impact on performance.
Document:
◆ StatementMacros
std::vector clang::format::FormatStyle::StatementMacros
A vector of macros that should be interpreted as complete statements.
Typical macros are expressions, and require a semi-colon to be added; sometimes this is not the case, and this allows to make clang-format aware of such cases.
For example: Q_UNUSED
Definition at line 1061 of file Format.h.
Referenced by clang::format::FormatTokenLexer::FormatTokenLexer(), clang::format::getLLVMStyle(), llvm::yaml::MappingTraits< FormatStyle >::mapping(), and operator==().
Solution:
build clang from source/wait for llvm/clang8 release, then
put StatementMacros ['QUERY_BEGIN()', 'QUERY_NORESULT()', 'QUERY_END()'] into your .clang-format.
Workaround for old clang-format
// clang-format off
void unformatted_code ;
// clang-format on
Turn off clang-format in this macro statements.

clang-format 3.7 added support for this under the names MacroBlockBegin and MacroBlockEnd. These config options are weirder than the newer-style (Attribute|Statement|If|Foreach)Macros options (which take lists); the older-style MacroBlock(Begin|End) options take regular expressions, which means that if you have multiple begin/end macros, you must glue them together like this:
MacroBlockBegin: '(FIRST_MACRO|SECOND_MACRO)'
Anyway, for your exact input, and this .clang-format file:
$ cat .clang-format
---
Language: Cpp
BasedOnStyle: LLVM
MacroBlockBegin: 'QUERY_BEGIN'
MacroBlockEnd: 'QUERY_END'
...
clang-format 14.0.6 produces this formatted output:
#define QUERY_BEGIN()
#define QUERY_NORESULT()
#define QUERY_END()
void foo() {
int a = 0;
QUERY_BEGIN()
a = 1;
QUERY_NORESULT()
a = 2;
QUERY_END()
}

Related

silence warnings about unused variables/functions at the point of their conditionally compiled usage

So in doctest (my testing framework) the user can disable all tests by defining the DOCTEST_CONFIG_DISABLE identifier which makes the following code and macros:
TEST_CASE("name") {
int a = 5;
int b = 6;
CHECK(a == b);
}
turn into the following after the preprocessor:
template<typename T>
void some_anon_func_123() {
int a = 5;
int b = 6;
}
that means that the self-registering test case is turned into an uninstantiated template function and the CHECK() macro (which functions as an if statement checking the condition) into a no-op - like this:
#define CHECK(x) ((void)0) // if disabled
However if the user has factored such testing code in a separate function like this:
static int g() {
std::cout << "called!" << std::endl;
return 42;
}
static void f() {
int a = 5;
CHECK(a == g());
}
TEST_CASE("name") {
f();
}
then there will be warnings for unused functions and unused variables. doctest prides itself with producing 0 warnings even on the most aggressive levels so this is unacceptable.
I tried using the ((void) ...) trick by passing it the macro argument like this:
#define CHECK(x) ((void)(x))
and that indeed silenced the warnings (atleast for a and g()) but there is still code being generated for that statement - if I invoke the f() function from my main() I will see the called! string printed in the console. This is undesirable since I want the compilation to be as fast as possible when test cases and asserts are disabled from the build (by using the DOCTEST_CONFIG_DISABLE identifier). If a user has 100 000 asserts and builds with them disabled he wouldn't want all that unnecessary codegen and compile time overhead for macros that are supposed to be disabled (the CHECK() one).
__attribute__((unused)) has to be used at the point of declaration of a variable - I cannot stick it in the CHECK() macro (or can I? I don't know...).
Not sure if _Pragma() could help - and even if it could - it is known to have issues with GCC:
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=55578
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=69543
Is there a solution to my problem - like perhaps passing the expression to some template or whatever...? (C++98 solution needed)
I explained my problem in excruciating detail only because I often get accused of the XY problem...
EDIT:
A C++11 solution is OK too - some C++11 features have started to conditionally creep into the library anyway...
So, you want to "lie" to the compiler that you're using a function which you're not actually calling. So how to use a piece of code without executing it?
It seems that the only thing that works on all popular compilers is a C++11-only solution - a lambda which is never called:
#define CHECK(x) [&](){ ((void)(x)); }
If you absolutely need a c++98 solution, a sizeof will also work on many compilers, MSVC being a notable exception:
#define CHECK(x) sizeof(x)
MSVC will still warn for uncalled functions in the expression x.
I guess for maximum coverage you could employ a combination of the two.

C++ class generation with pre-processor directives

I am trying to generate a class given below with the help of recursive Macros/ pre-processor directives. I cannot use templates as I am building the type (a class). The macro users must be able to create this class without repeating the variables. I do not want to use containers for the variables as they can have meaningful names.
class IInterface;
class XYZ
{
int Mark1, Mark2, Mark3 /* variables to be passed */;
int count;
XYZ(IInterface * I)
{
count = 0;
// initialization values to be passed
Mark1 = 10; count++; I -> add(Mark1);
Mark2 = 20; count++; I -> add(Mark2);
Mark3 = 30; count++; I -> add(Mark3);
}
};
I am trying to put place holders and then expand them.
#define CLASS(_name) class _name {\
int VARS; \
int count; \
_name(IInterface * I) \
{ \
count = 0; \
VAR = val; count++; I -> add(VAR); \
} \
};
#define INIT // expansion code
CLASS(XYZ)
INIT(Mark1, 10) // variables should be sent only once for all the placeholders
INIT(Mark2, 20)
INIT(Mark3, 30)
How can I expand INIT to replace the placeholders?
I would like to know if this is feasible/ recommended.
This is not perhaps the "answer" directly to the question but achieves the same aim.
Macros in general are "evil" but can be useful at times. Here, however, they remain evil as anyone using the class later on will be hard-pressed to work out its actual definition, and errors will be much harder to decipher.
Therefore the recommendation is to use a scripting language as a pre-build step that can read in the configuration of your classes and generate the C++ files from it.
Then users of the classes will see actual C++ headers that look comprehensible.
Perl or Python might be used as the scripting language for this purpose. I would probably choose Perl.
You would then make this a pre-build step.
The generated headers would be the target, the scripted definition which is in a format you decide is the input, and a make script would know therefore if the targets are up-to-date.
For the input (class definition) file, you could use XML or JSON format, both of which give you nested key-value pairs with repeating groups. Whichever you choose has the advantages that
They are well known formats, understood by developers who may need to read or write them
There is already code to parse them so you won't need to write an actual parser, instead you'd just use the parsed data to generate your output file.

Initialize global array of function pointers at either compile-time, or run-time before main()

I'm trying to initialize a global array of function pointers at compile-time, in either C or C++. Something like this:
module.h
typedef int16_t (*myfunc_t)(void);
extern myfunc_array[];
module.cpp
#include "module.h"
int16_t myfunc_1();
int16_t myfunc_2();
...
int16_t myfunc_N();
// the ordering of functions is not that important
myfunc_array[] = { myfunc_1, myfunc_2, ... , myfunc_N };
func1.cpp, func2.cpp, ... funcN.cpp (symbolic links to a single func.cpp file, so that different object files are created: func1.o, func2.o, func3.o, ... , funcN.o. NUMBER is defined using g++ -DNUMBER=N)
#include "module.h"
#define CONCAT2(x, y) x ## y
#define CONCAT(x, y) CONCAT2(x, y)
int16_t CONCAT(myfunc_, NUMBER)() { ... }
When compiled using g++ -DNUMBER=N, after preprocessing becomes:
func1.cpp
...
int16_t myfunc_1() { ... }
func2.cpp
...
int16_t myfunc_2() { ... }
and so on.
The declarations of myfunc_N() and the initialization of myfunc_array[] are not cool, since N changes often and could be between 10 to 200. I prefer not to use a script or Makefile to generate them either. The ordering of functions is not that important, i can work around that. Is there a neater/smarter way to do this?
How To Make a Low-Level Function Registry
First you create a macro to place pointers to your functions in a special section:
/* original typedef from question: */
typedef int16_t (*myfunc)(void);
#define myfunc_register(N) \
static myfunc registered_##myfunc_##N \
__attribute__((__section__(".myfunc_registry"))) = myfunc_##N
The static variable name is arbitrary (it will never be used) but it's nice to choose an expressive name. You use it by placing the registration just below your function:
myfunc_register(NUMBER);
Now when you compile your file (each time) it will have a pointer to your function in the section .myfunc_registry. This will all compile as-is but it won't do you any good without a linker script. Thanks to caf for pointing out the relatively new INSERT AFTER feature:
SECTIONS
{
.rel.rodata.myfunc_registry : {
PROVIDE(myfunc_registry_start = .);
*(.myfunc_registry)
PROVIDE(myfunc_registry_end = .);
}
}
INSERT AFTER .text;
The hardest part of this scheme is creating the entire linker script: You need to embed that snippet in the actual linker script for your host which is probably only available by building binutils by hand and examining the compile tree or via strings ld. It's a shame because I quite like linker script tricks.
Link with gcc -Wl,-Tlinkerscript.ld ... The -T option will enhance (rather than replace) the existing linker script.
Now the linker will gather all of your pointers with the section attribute together and helpfully provide a symbol pointing before and after your list:
extern myfunc myfunc_registry_start[], myfunc_registry_end[];
Now you can access your array:
/* this cannot be static because it is not know at compile time */
size_t myfunc_registry_size = (myfunc_registry_end - myfunc_registry_start);
int i;
for (i = 0; i < myfunc_registry_size); ++i)
(*myfunc_registry_start[i])();
They will not be in any particular order. You could number them by putting them in __section__(".myfunc_registry." #N) and then in the linker gathering *(.myfunc_registry.*), but the sorting would be lexographic instead of numeric.
I have tested this out with gcc 4.3.0 (although the gcc parts have been available for a long time) and ld 2.18.50 (you need a fairly recent ld for the INSERT AFTER magic).
This is very similar to the way the compiler and linker conspire to execute your global ctors, so it would be a whole lot easier to use a static C++ class constructor to register your functions and vastly more portable.
You can find examples of this in the Linux kernel, for example __initcall is very similar to this.
I was going to suggest this question is more about C, but on second thoughts, what you want is a global container of function pointers, and to register available functions into it. I believe this is called a Singleton (shudder).
You could make myfunc_array a vector, or wrap up a C equivalent, and provide a function to push myfuncs into it. Now finally, you can create a class (again you can do this in C), that takes a myfunc and pushes it into the global array. This will all occur immediately prior to main being called. Here are some code snippets to get you thinking:
// a header
extern vector<myfunc> myfunc_array;
struct _register_myfunc {
_register_myfunc(myfunc lolz0rs) {
myfunc_array.push_back(lolz0rs);
}
}
#define register_myfunc(lolz0rs) static _register_myfunc _unique_name(lolz0rs);
// a source
vector<myfunc> myfunc_array;
// another source
int16_t myfunc_1() { ... }
register_myfunc(myfunc_1);
// another source
int16_t myfunc_2() { ... }
register_myfunc(myfunc_2);
Keep in mind the following:
You can control the order the functions are registered by manipulating your link step.
The initialization of your translation unit-scoped variables occurs before main is called, i.e. the registering will be completed.
You can generate unique names using some macro magic and __COUNTER__. There may be other sneaky ways that I don't know about. See these useful questions:
Unnamed parameters in C
Unexpected predefined macro behaviour when pasting tokens
How to generate random variable names in C++ using macros?
Your solution sounds much too complicated and error prone to me.
You go over your project with a script (or probably make) to place the -D options to the compiler, anyhow. So I suppose you are keeping a list of all your functions (resp. the files defining them).
I'd use proper names for all the functions, nothing of your numbering scheme and then I would produce the file "module.cpp" with that script and initialize the table with the names.
For this you just have to keep a list of all your functions (and perhaps filenames) in one place. This could be easier be kept consistent than your actual scheme, I think.
Edit: Thinking of it even this might also be overengineering. If you have to maintain a list of your functions somewhere in any case, why not just inside the file "module.cpp"? Just include all the header files of all your functions, there, and list them in the initializer of the table.
Since you allow C++, the answer is obviously yes, with templates:
template<int N> int16_t myfunc() { /* N is a const int here */ }
myfunc_array[] = { myfunc<0>, myfunc<1>, myfunc<2> }
Now, you might wonder if you can create that variable-length initializer list with some macro. The answer is yes, but the macro's needed are ugly. So I'n not going to write them here, but point you to Boost::Preprocessor
However, do you really need such an array? Do you really need the name myfunc_array[0] for myfunc<0> ? Even if you need a runtime argument (myfunc_array[i]) there are other tricks:
inline template <int Nmax> int16_t myfunc_wrapper(int i) {
assert (i<Nmax);
return (i==Nmax) ? myfunc<Nmax> : myfunc_wrapper(i-1);
}
inline int16_t myfunc_wrapper(int i) {
return myfunc_wrapper<NUMBER>(i); // NUMBER is defined on with g++ -DNUMBER=N
}
Ok I worked out a solution based on Matt Joiner's tip:
module.h
typedef int16_t (*myfunc_t)(void);
extern myfunc_array[];
class FunctionRegistrar {
public:
FunctionRegistrar(myfunc_t fn, int fn_number) {
myfunc_array[fn_number - 1] = fn; // ensures correct ordering of functions (not that important though)
}
}
module.cpp
#include "module.h"
myfunc_array[100]; // The size needs to be #defined by the compiler, probably
func1.cpp, func2.cpp, ... funcN.cpp
#include "module.h"
static int16_t myfunc(void) { ... }
static FunctionRegistrar functionRegistrar(myfunc, NUMBER);
Thanks everyone!

How to find assignments with no effect?

In the process of automatically renaming many variables in a big project I may have created a lot of things like these:
class Foo {
int Par;
void Bar(int Par) {
Par = Par; // Nonsense
}
};
Now I need to identify those locations to correct them. E.g. into "this->Par = Par;".
Unfortunately the Visual C++ Compiler des not give me any comment about it even with all warnings on.
I remember there once was a warning about it. It said "Code has no effect" or something. But it seems to be gone maybe because some people used that practice to avoid "unreferenced parameter" warnings.
Is there a way to re-activate that warning?
Does GCC warn here?
Any Idea?
A couple of compilers can generate warnings on this:
GCC and Clang can warn on code like this if you add the -Wshadow option. (Specifically, while they don't warn about the meaningless assignment, they do warn about the local variable Par shadowing the member variable Par - you may or may not like this.)
Embarcadero C++Builder does not warn that Par = Par is useless, but it can warn that Par isn't used after it's assigned to, which should meet your needs.
I suspect a tool like PC-Lint could also identify code like this.
Another solution is to mark your parameters as const:
class Foo {
int Par;
void Bar(const int Par) {
Par = Par; // Compiler error!
}
};
const on pass-by-value parameters is not part of the function signature, so you only need to add it to the function definitions within your .cpp file, not your function declarations within your .h file. In other words, it's legal to do this:
// foo.h
class Foo {
int Par;
void Bar(int Par);
};
// foo.cpp
void Foo::Bar(const int Par) { ... }
As kaptnole pointed out, the regex I crafted could be used directly in visual studio. Your pattern is:
^[\s\t]*([a-zA-Z_0-9])[\s\t]=[\s\t]\1[\s\t];[\s\t]*$
Follow the directions listed here:
http://msdn.microsoft.com/en-us/library/2k3te2cs%28VS.80%29.aspx
...and happy finding (without ever touching Perl!).
This perl one liner will do it for you:
perl -n -e'/^[\s\t]*([a-zA-Z_0-9]*)[\s\t]*=[\s\t]*\1[\s\t]*;[\s\t]*$/&&print "$. $_"' test_me && echo
I tested it on a file containing the following and it correctly detected all matches:
hi = hi;
hi= hi ;
hi=hi ;
Output....
xxxxx#yyyy% perl -n -e'/[\s\t]*([a-zA-Z_0-9]*)[\s\t]*=[\s\t]*\1[\s\t]*;[\s\t]*$/&&print "$. $_"' test_me && echo
1 hi = hi;
2 hi= hi ;
3 hi=hi ;
xxxxx#yyyy%
My first thought was to do it in Awk, but apparently Awk doesn't store its matches! :(
But hey, this Perl script is pretty snazzy itself... it even prints the line numbers of the find!
EDIT 1
And to answer your other question, I compiled a simple test program with such an assignment inside main with the "-pedantic" and "-Wall" flags using gcc and g++ and received no warnings in either... so I guess it doesn't warn you of this kind of redundancy.
Here's my test program:
int main (int argc, char *argv[]) {
int bob=5;
bob=bob;
return 0;
}
EDIT 2
Please note my above perl script does NOT check to see if there's a local variable of an identical name inside a function. In that case the statement might be valid, but poor style (still might be good to warn about).
And as Josh points out, the flag "-Wshadow" WILL warn about this in gcc/g++ in this specialized case.
I would suggest following Josh's advice about using const for static function arguments. In fact, any variable not passed by reference should generally be const
e.g.
void hello_world_print_numbers(int number_1, int number_2, int number_3) {
...
}
is a misassignment waiting to happen, so instead use:
void hello_world_print_numbers(const int number_1, const int number_2, const int number_3) {
...
}
...likewise in general with pointers, except in the case of passed pointers to arrays (and be careful there to pass in proper array bounds!).
void hello_world_print_numbers(const int * number_1, const int * number_2, const int * number_3) {
...
}
EDIT 3
I forgot my ^ at the start of my regex. While seemingly trivial this causes it to improperly tag assignments of type my_class->name=name;. This was wisely pointed out by RC. The regex is now fixed and should no longer have this issue. Thanks RC!
As Brian said in his comment, this is one really good argument for having a naming convention which differentiates between member variables and function arguments for classes (of which the "m_" prefix is just one example). I'd suggest that approach, lest you need to repeat the search process regularly down the road.
You can try this, though I would expect that you could find some false positives or some cases where it may miss, but it should find the straight forward ones.## Heading ##
I took your class and put it inside a file Foo.h as:
class Foo {
int Par;
void Bar(int Par) {
Par = Par; // Nonsense
Par=Par; // Nonsense
Par = Par; // Nonsense
Par = Par ; // Nonsense
this->x = x; // Do not match this
}
};
Then I created the following Perl Script called match.pl
#!/usr/bin/perl
use strict;
my $filename = $ARGV[0];
open(my $F, $ARGV[0]) || die("Cannot open file: $filename");
print "Procesing File: $filename\n";
my $lineNum = 0;
while (<$F>)
{
$lineNum++;
chomp;
my $line = $_;
if ($line =~ /(?:^|\s+)(\w+?)\s*=\s*\1\s*;/)
{
print "\t$filename:$lineNum: $line\n";
}
}
Then you can run it.
%> ./match.pl Foo.h
Procesing File: Foo.h
Foo.h:4: Par = Par; // Nonsense
Foo.h:5: Par=Par; // Nonsense
Foo.h:6: Par = Par; // Nonsense
Foo.h:7: Par = Par ; // Nonsense
Then on Linux (I'm sure there is a similar command on Windows) you can do:
%> find *.cpp *.h -exec ./match.pl {} \;
Procesing File: test.cpp
Procesing File: test2.cpp
Procesing File: test3.cpp
Procesing File: Foo.h
Foo.h:4: Par = Par; // Nonsense
Foo.h:5: Par=Par; // Nonsense
Foo.h:6: Par = Par; // Nonsense
Foo.h:7: Par = Par ; // Nonsense
I am thinking about writing a script to go over the files and detecting lines containing the pattern
exp=exp;
ignoring all white spaces in the line.

How to generate random variable names in C++ using macros?

I'm creating a macro in C++ that declares a variable and assigns some value to it. Depending on how the macro is used, the second occurrence of the macro can override the value of the first variable. For instance:
#define MY_MACRO int my_variable_[random-number-here] = getCurrentTime();
The other motivation to use that is to avoid selecting certain name to the variable so that it be the same as a name eventually chosen by the developer using the macro.
Is there a way to generate random variable names inside a macro in C++?
-- Edit --
I mean unique but also random once I can use my macro twice in a block and in this case it will generate something like:
int unique_variable_name;
...
int unique_variable_name;
In this case, to be unique both variable names have to be random generated.
Try the following:
// One level of macro indirection is required in order to resolve __COUNTER__,
// and get varname1 instead of varname__COUNTER__.
#define CONCAT(a, b) CONCAT_INNER(a, b)
#define CONCAT_INNER(a, b) a ## b
#define UNIQUE_NAME(base) CONCAT(base, __COUNTER__)
void main() {
int UNIQUE_NAME(foo) = 123; // int foo0 = 123;
std::cout << foo0; // prints "123"
}
__COUNTER__ may have portability issues. If this is a problem, you can use __LINE__ instead and as long as you aren't calling the macro more than once per line or sharing the names across compilation units, you will be just fine.
use __COUNTER__ (works on gcc4.8, clang 3.5 and Intel icc v13, MSVC 2015)
#define CONCAT_(x,y) x##y
#define CONCAT(x,y) CONCAT_(x,y)
#define uniquename static bool CONCAT(sb_, __COUNTER__) = false
Add M4 to your build flow? This macro language has some stateful capabilities, and can successfully be intermingled with CPP macros. This is probably not a standard way to generate unique names in a C environment, though I've been able to sucessfully use it in such a manner.
You probably do not not want random, BTW, based on the way you posed your question. You want unique.
You could use __FILE__ and __LINE__ in the macro expansion to get you the uniqueness you seem to be going for... those metavariables get defined within the source file context, so be careful to make sure you get what you are looking for (e.g., perils of more than one macro on the same line).
Generating unique names in the preprocessor is difficult. The closest you can get is to mangle __FILE__ and __LINE__ into the symbol as popcnt suggests. If you really need to generate unique global symbol names, then I would follow his suggestion about using something like M4 or a Perl script in your build system instead.
You might not need unique names. If your macro can impose a new scope, then you can use the same name since it will simply shadow other definitions. I usually follow the common advice of wrapping macros in do { ... } while (0) loops. This only works for macros which are statements - not expressions. The macro can update variables using output parameters. For example:
#define CALC_TIME_SINCE(t0, OUT) do { \
std::time_t _tNow = std::time(NULL); \
(OUT) = _tNow - (t0); \
} while (0)
If you follow a few rules, you are usually pretty safe:
Use leading underscores or similar naming conventions for symbols defined within the macro. This will prevent problems associated with a parameter using the same symbol from occurring.
Only use the input parameters once and always surround them with parentheses. This is the only way to make macros work with expressions as input.
Use the do { ... } while (0) idiom to ensure that the macro is only used as a statement and to avoid other textual replacement problems.
Instead of having the preprocesser create a name, you could possibly let the macro user give you a name.
#define MY_MACRO(varname) int varname = getCurrentTime();
I needed something similar for a case where I didn't have any profiling tools, but I wanted to count how many threads were inside a particular block of code as well as the amount of time (ticks) spent in that block of code by each thread, In this case every block needed a unique static variable accessible to all threads, and I needed to later reference that variable to incr (I used a logging API rather than printf in the actual code, but this works as well). At first I thought I was very clever by doing the following:
#define PROF_START { \
static volatile int entry_count##___FUNCTION__##__LINE__ = 0; int *ptc = &entry_count##___FUNCTION__##__LINE__; \
clock_t start, end; \
start = times(0); \
(*ptc)++;
But then I realized this is just silly and the C compiler will simply do this for you, as long as each "static" declaration is its own block:
#include <stdio.h>
#include <sys/times.h>
#define PROF_START { \
static int entry_count = 0; \
clock_t start, end; \
start = times(0); \
entry_count++;
#define PROF_END \
end = times(0); \
printf("[%s:%d] TIMER: %ld:%d\n" , __FUNCTION__, __LINE__, end-start, entry_count); \
entry_count--; \
}
Note the open/close brackets in each macro. This isn't strictly thread-safe, but for my profiling purposes I could assume the incr and decr operations were atomic. Here's a recursion sample which uses the macros
#define ITEM_COUNT 5
struct node {
int data;
struct node *next;
};
revsort(struct node **head)
{
struct node *current = *head;
struct node *next_item;
while (current->next)
{
PROF_START
next_item = current->next;
current->next = next_item->next;
next_item->next = *head;
*head = next_item;
PROF_END
}
}
rrevsort(struct node **head)
{
struct node *current = *head;
struct node *next_item = current->next;
PROF_START
current->next = 0;
if (next_item)
{
*head = next_item;
rrevsort(head);
next_item->next = current;
}
PROF_END
}
printnode(struct node *head)
{
if (head)
{
printf("%d ", head->data);
printnode(head->next);
}
else
printf("\n");
}
main()
{
struct node node_list[ITEM_COUNT];
struct node *head = &node_list[0];
int i;
for (i=0; i < ITEM_COUNT - 1; i++)
{
PROF_START
node_list[i].data = i;
node_list[i].next = &node_list[i+1];
PROF_END
}
node_list[i].data = i;
node_list[i].next = 0;
printf("before\n");
printnode(head);
revsort(&head);
printf("after\n");
printnode(head);
rrevsort(&head);
printf("before\n");
printnode(head);
}
Extra hint, the above program is a common interview question. Excerpt from "nm -A":
macro:0804a034 b entry_count.1715
macro:0804a030 b entry_count.1739
macro:0804a028 b entry_count.1768
macro:0804a02c b entry_count.1775
Here is a succinct macro definition to generate the singleton pattern above.
#define SINGLETON_IMPLIMENTATION(CLASS_NAME) static CLASS_NAME *g##CLASS_NAME = nil; + (CLASS_NAME *)instance { #synchronized(self) { if (g##CLASS_NAME == nil) g##CLASS_NAME = [self new]; } return g##CLASS_NAME; }
#define SINGLETON_DECLARATION(CLASS_NAME) + (CLASS_NAME *)instance;
While I don't think its even possible, you should seriously consider making a class out of this.
If you want a random element in a random array to hold a certain value, you can do this:
std::vector< std::vector<int> > m_vec;
Then wrap it in a class, so the developer can only set a number:
void set(int foo)
{
m_vec[random()][random()] = foo;
}
Is there any reason why you want it a macro? Random variable name sounds dangerous, what if it picks something already defined somewhere else in the code?