2

Let's say this is a preprocessor definition before function f():

#define write std::cout << "test";
write
void f()
{
    //...
}

and this is result of that macro:

std::cout << "test"
void f()
{
    //...
}

How do I write that macro so it will skip function and also insert some code behind the function so that the result will be something like this:

std::cout << "test";
void f()
{
    //...
}
std::cout << "test";

You know what I mean: a macro (or something else) that skips some code and inserts multiple lines.

1 Answer 1

6

You can pass the function itself as an argument to the macro:

#define write(...)       \
    std::cout << "test"; \
    __VA_ARGS__          \
    std::cout << "test";

write(
void f()
{
    //...
})

This particular example, of course, is ill-formed because there are statements outside of functions.

If you are actually interested in printing text at the beginning and end of a function, your best bet is to create a class that prints the text in its constructor and destructor, and declare an instance of that type at the beginning of the function.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 A nice solution but one that should be avoided. class solution recommended instead.
+1 A class-based constructor/destructor solution is the way to go: you could build elaborate things with it. We used it for tracing method entries and exits, and even to capture crash stacks in production environments.
Oh thanks, that's awsome :D, what do you mean by "create class option" will I put that object(of that class) at the beginig inside a function or outside? thanks. how does that work :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.