I would like to add a single line of code at the beginning of each function in my c++ visual studio 2010 project.
It would take months to manually add a line into each function. Are there any quick way or tool to solve this problem?
Edit: I would like to add a checkpoint for debugging purposes in every function in my project. I have a macro to handle adding checkpoints so the problem is now adding one single line of code. it could be anything, a macro, a console output, etc.
For example, have hundreds of functions:
void func1()
{
//code
}
int func2()
{
//code
}
char* func3()
{
//code
}
/* more functions */
bool func100()
{
//code
}
//I want them to become:
void func1()
{
myMacro;
//code
}
int func2()
{
myMacro;
//code
}
char* func3()
{
myMacro;
//code
}
/* more functions */
bool func100()
{
myMacro;
//code
}
You don't need to hack up your code to get function instrumentation! See here for example: http://www.drdobbs.com/automatic-code-instrumentation/184403601
The short story is that MSVC has _penter, a facility for doing pretty much what you're trying to accomplish here, but without modifying most of the source code.
As an aside, a standard term for what you asked about (adding code before function calls) is Aspect Oriented Programming.
MSVC supports keyboard macro recording (for c++ keyboard layout it is Ctrl+Shift+R - to start and Ctrl+Shift+P to stop). Define regular expression to find signature of function after that store keyboard macro something like following sequence:
F3 (for next function entry)
key down - to seek '{'
Ctrl + '}' to seek closing bracket
.... add extra line there ....
When keyboard-macro ready press Ctrl+R - to play this macro. The thousands of line handled very quickly
Related
I have a question about the possibile use of goto in a C++ code: I know that goto shall be avoided as much as possibile, but in this very particular case I'm having few difficulties to find good alternatives that avoid using multiple nested if-else and/or additional binary flags...
The code is like the following one (only the relevant parts are reported):
// ... do initializations, variable declarations, etc...
while(some_flag) {
some_flag=false;
if(some_other_condition) {
// ... do few operations (20 lines of code)
return_flag=foo(input_args); // Function that can find an error, returning false
if(!return_flag) {
// Print error
break; // jump out of the main while loop
}
// ... do other more complex operations
}
index=0;
while(index<=SOME_VALUE) {
// ... do few operations (about 10 lines of code)
return_flag=foo(input_args); // Function that can find an error, returning false
if(!return_flag) {
goto end_here; // <- 'goto' statement
}
// ... do other more complex operations (including some if-else and the possibility to set some_flag to true or leave it to false
// ... get a "value" to be compared with a saved one in order to decide whether to continue looping or not
if(value<savedValue) {
// Do other operations (about 20 lines of code)
some_flag=true;
}
// ... handle 'index'
it++; // Increse number of iterations
}
// ... when going out from the while loop, some other operations must be done, at the moment no matter the value of some_flag
return_flag=foo(input_args);
if(!return_flag) {
goto end_here; // <- 'goto' statement
}
// ... other operations here
// ... get a "value" to be compared with a saved one in order to decide whether to continue looping or not
if(value<savedValue) {
// Do other operations (about 20 lines of code)
some_flag=true;
}
// Additional termination constraint
if(it>MAX_ITERATIONS) {
some_flag=false;
}
end_here:
// The code after end_here checks for some_flag, and executes some operations that must always be done,
// no matter if we arrive here due to 'goto' or due to normal execution.
}
}
// ...
Every time foo() returns false, no more operations should be executed, and the code should execute the final operations as soon as possible. Another requirement is that this code, mainly the part inside the while(index<=SOME_VALUE) shall run as fast as possible to try to have a good overall performance.
Is using a 'try/catch' block, with the try{} including lots of code inside (while, actually, the function foo() can generate errors only when called, that is in two distinct points of the code only) a possibile alternative? Is is better in this case to use different 'try/catch' blocks?
Are there other better alternatives?
Thanks a lot in advance!
Three obvious choices:
Stick with goto
Associate the cleanup code with the destructor of some RAII class. (You can probably write it as the delete for a std::unique_ptr as a lambda.)
Rename your function as foo_internal, and change it to just return. Then write the cleanup in a new foo function which calls foo_internal
So:
return_t foo(Args...) {
const auto result = foo_internal(Args..);
// cleanup
return result;
}
In general, your function looks too long, and needs decomposing into smaller bits.
One way you can do it is to use another dummy loop and break like so
int state = FAIL_STATE;
do {
if(!operation()) {
break;
}
if(!other_operation()) {
break;
}
// ...
state = OK_STATE;
} while(false);
// check for state here and do necessary cleanups
That way you can avoid deep nesting levels in your code beforehand.
It's C++! Use exceptions for non-local jumps:
try {
if(some_result() < threshold) throw false;
}
catch(bool) {
handleErrors();
}
// Here follows mandatory cleanup for both sucsesses and failures
Is it possible to send control from other file to main file using GOTO statement if yes please tell. if is it not possible please tell me another method.
main.cc
{
outer: // label where I want to return
callingfunc()
//control go into calling func
}
source.cc //another source file with a class
class myclass
{
public:
callingfunc();
};
callingfunc()
{
some code
goto outer; //from here I want to send control to outer label in file **main.cc**
}
You can only goto labels in the same function, and it's very poor practice to break a function across source files (which is only possible if an #included file contains the first part of the function). To transfer execution, you normally want to use function calls (whether to a hardcoded function or one identified by e.g. a function pointer or std::function<>) and return statements, sometimes throw and exceptions, and very very rarely something unusual like setjmp/longjmp (if you need to ask this question you shouldn't be playing with those latter functions). You should explain more about your program - ideally post some code - if you want specific advice on what suits your needs.
Update: now you've posted some code, you could consider something like this...
// source.h
enum Flow { Outer, Continue }; // whatever names make sense to you...
Flow callingfunc();
// main.cc
#include "source.h"
if (callingfunc(...) == Outer) goto outer;
// source.cc
#include "source.h"
Flow callingfunc() { ...; return Outer; ... return Continue; }
It's best to try to find a better name than "Outer"... something that communicates the condition that callingfunc has found or the consequent processing it's recommending (e.g. Timeout, Can_Retry, Model_Unsolvable).
I'm writing a short text-adventure game and that game is ready, but now I want to do something with a main menu. Note that the whole game is in DOS.
This is what I want to achieve:
Create a main menu in the following way, but using while and switch loops. The switch loop will contain cases (case 1:, case 2:, case 3:, etc.) with the following options (which will cout above the loops)
cout << "[1] Play\n";
cout << "[2] Credits\n";
cout << "[3] Exit\n";
Now, the text-adventure game is too big to just put in this loop as it becomes increasingly hard to read because of nesting. There are loops in the game itself too, also while and switch loops. What I want to do now is something like the following, but I don't know how to do this. I will write it in psuedocode:
*open file game_name.cpp*
If player presses 1
Insert actual_game.cpp
Play game until over or user presses escape
else if player presses 2
Show credits
Return to main menu
else if player presses 3
Terminate the session
else
Shows the player that an invalid option has been chosen
The point is that I want to include multiple .cpp files instead of putting all the code in one single file (the actual_game.cpp). What is the best way to do this?
This question and answer is very similar to yours, take a look:
Link
Let me know if something is unclear in there. The bottom line is that you don't insert code files - those don't exist anyway after you compile your program. You call functions in response to each condition - those individual functions will, in turn, execute the relevant logic. You need to organize your game into a set of functions, where each function performs one particular job in the game (and likely call ever more specialized functions that handle the various locations in your game, etc.)
Here's an example:
// In GameFunctions.h:
bool StartGame ();
bool ShowCredits ();
bool ExitGame ();
// Add all function definitions here or create multiple header files to hold
// groups of function definitions. Include these headers files in your CPP files.
// In GameFunctions.cpp:
#include <iostream>
#include "GameFunctions.h"
using namespace std;
int main ( int argc, const char* argv[] )
{
int nKeyPress; // this holds the key pressed by the user
bool bContinue = true;
while ( bContinue )
{
... // read a key here into nKeyPress
switch ( nKeyPress )
{
case 1:
bContinue = StartGame ();
break;
case 2:
bContinue = ShowCredits ();
break;
case 3:
bContinue = ExitGame ();
break;
}
}
}
...
bool StartGame ()
{
// initialize your game here
InitGame ();
// Show the first room of your game and start waiting for
// user input (the user making various selections in the game).
// You'll invoke other rooms from this function as you respond to
// user selections.
ShowRoom ( 1 );
return ( true );
}
bool ShowCredits ()
{
... // show credits here
return ( true );
}
bool ExitGame ()
{
// do cleanup (if you have any to do) here
return ( false );
}
You can also break up your game code into multiple .cpp and .h files to group your functions into logical groups. Even if you don't use classes, having all your code in a single .cpp file is usually a bad idea, unless your game is very, very short. So you can create multiple .cpp files, for example, one for each room: each .cpp file will hold the code to handle a particular room in your game. You'll need the function definitions in a header file and you need to include all header files in a particular .cpp file that you intend to use. (You don't need to include every .h in every .cpp, though - you only need those headers that contain definitions that you intend to use in a single .cpp.)
At the end, your game will be made up of several .cpp and .h files and will have a number of functions: some will read user input, some will display messages on the screen, some may keep track of the user's score, some will initialize a room before the player first enters it, etc.
You'll likely need other header files from the standard C or C++ library, depending on what standard features you'll try to use.
For C++ compiler to use the function it need only to know the function's signature, not the whole function. After all .cpp files are compiled the linker must know about the whole functions, so that it can link all the parts into an application. Function's signature (also called "function declaration") is usually stored in header file (example.h), and the actual function (also called "function definition") is usually stored in source file (example.cpp). In one .cpp file you can call the function defined in another .cpp file, just add an include line where you tell the compiler where to look for that function's declaration (#include "example.h"):
-----------------
Main project file
-----------------
#include "actual_game.h"
#include "credits.h"
int main()
{
for (;;)
{
PrintMainMenu();
int choice = GetUsersChoice();
if (choice == CHOICE_PLAY_GAME)
PlayTheGame(); // This function is found in files actual_game.h and .cpp
else if (choice == CHOICE_SHOW_CREDITS)
ShowCredits(); // This function is found in files credits.h and .cpp
else if (choice == CHOICE_TERMINATE)
break;
else
ShowInvalidOptionMessage();
}
return 0;
}
------------------
File actual_game.h
------------------
void PlayTheGame();
--------------------
File actual_game.cpp
--------------------
#include "actual_game.h"
void PlayTheGame()
{
// The body of the function. If this function is very large and difficult to
// read by humans then divide it somehow to several other functions, that can
// be put in several files, and so easier to handle and maintain
}
Specifically, I want to write a macro that
1) allows me to set a breakpoint
2) does nothing else
3) causes no compiler warnings
#define NO_OP ((void)0)
void main()
{
bool b = true;
if (b)
NO_OP; // I try to set a breakpoint here, but
} // it jumps to here (in Visual Studio 2010)
I also tried
#define NO_OP (assert(1)) // doesn't work
#define NO_OP (sizeof(int)) // doesn't work
#define NO_OP __asm{} // doesn't work
#define NO_OP do {(void)0;} while(0) // warning: conditional is constant
The only thing that works so far is the cringe-worthy
#define NO_OP { int x = 0; x = x; }
There has to be a better way.
EDIT
Thanks Blorgbeard, __asm{ nop } does indeed work. But I just realized that anything with braces is less than perfect (problematic?) because it leaves a useless semi-colon hanging there after it. (Later) I don't know squat about assembler but I tried removing the braces, and voila! There's the answer: __asm nop
Thanks!
FOR THE CURIOUS
Here's a slightly less absurd example:
string token = GetNextToken();
if (!Ignore(token))
{
// process token
DoThis(token);
DoThat(token);
}
This code is complete -- as long as the program works correctly I don't care to know anything about ignored tokens. But at any given time (and without changing the code) I want to make sure that I'm not rejecting good tokens
string token = GetNextToken();
if (Ignore(token))
{
NO_OP; // when desired, set breakpoint here to monitor ignored tokens
}
else
{
// process token
DoThis(token);
DoThat(token);
}
An actual no-op instruction:
__asm nop
Perhaps you can do this:
#define BREAKPOINT __asm { int 3; }
This will call interrupt 3, which is the breakpoint interrupt. This will set a breakpoint in your code, which is compiled as part of your code.
Now, if you want just some operation that you can set a breakpoint on, which essentially does nothing, besides allowing you to break on that line. I think you have to compile your code without optimization for one thing, as a NO_OP as you've implemented is likely to be optimized out of the code by an optimizing compiler, with the optimization switches on.
The other point is, that this seems like a very strange thing to do. From my knowledge, one normally sets a breakpoint on a line of code one wants to look at. See what variable state's are, step one line at a time, etc. I don't really see how setting a breakpoint on a line of code with essentially no significance in your program, will help you debug anything.
C++03:
inline void __dummy_function_for_NO_OP () {}
#define NO_OP __dummy_function_for_NO_OP ()
int main () {
NO_OP;
}
C++11:
#define NO_OP [](){}()
int main () {
NO_OP;
}
On msvc x64 there is an intrinsic for this:
__nop;
Header file: <intrin.h>
doc: https://learn.microsoft.com/en-us/cpp/intrinsics/nop?view=msvc-170
How about __asm int 3? Also, are optimizations enabled? That could be the reason for the others failing (actually never tried to break on them).
You could define a global unsigned int debug_counter, then your "no-op" macro can be debug_counter++. Pretty sure the compiler won't remove that, but to be absolutely sure, put some code somewhere to print the value of the counter.
Define in myassert.h and include everywhere in your app (force include in Visual Studio?).
// Works cross-platform. No overhead in release builds
#ifdef DEBUG
// This function may need to be implemented in a cxx module if
// your compiler optimizes this away in debug builds
inline bool my_assert_func(const bool b)
{
// can set true/false breakpoints as needed
if (b) {
return true;
}
else {
return false;
}
}
#define myassert(b) assert(my_assert_func(b))
#else // RELEASE
// In release builds this is a NOP
#define myassert(b) ((void)0)
#endif
#define DEBUG_BREAKPOINT myassert(true)
Now you can:
string token = GetNextToken();
if (Ignore(token))
DEBUG_BREAKPOINT;
}
else {
// process token
DoThis(token);
DoThat(token);
}
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Are do-while-false loops common?
Is there a reason to have code like:
do {
// a lot of code that only needs to be run once
} while (FALSE);
when the code isn't defining a macro? I know it's a trick when it comes to macros, but is there a reason for it in normal code?
Well, it does allow you to use the break; (or continue) keyword for early exit if you have a need for that for some reason. That would be kinda ugly though. I'd really rather see it moved into its own routine, with the early exit implemented via a return; statement.
Well one reason for it would be if you want to break out at some point.
i.e.
do
{
//some code that should always execute...
if ( condition )
{
//do some stuff
break;
}
//some code that should execute if condition is not true
if ( condition2 )
{
//do some more stuff
break;
}
//further code that should not execute if condition or condition2 are true
}
while(false);
In certain situations the resulting code is a little bit more clear / easier to understand if written as above.
Such a construct is used as a kind of goto to be able to jump after the end of the loop using a break statement inside.
I would not do this but:
I looks slightly more logical than just braces
int main()
{
{
std::ifstream file("Data");
// DO STUFF
} // Data now closed.
// LOTS OF STUFF SO YOU CANT SEE file2 below.
// We can re-use data here as it was closed.
std::ofstream file2("Data");
// DO STUFF
}
An unobservant maintainer may see the braces and think.
What the heck and remove them
int main()
{
std::ifstream file("Data");
// DO STUFF
// LOTS OF STUFF SO YOU CANT SEE file2 below.
// FAIL. data is still open from before.
std::ofstream file2("Data");
// DO STUFF
}
I suppose using the while tick at least make syou think about it (though an unobservant maintainer may still remove it).
int main()
{
do
{
std::ifstream file("Data");
// DO STUFF
} while (false);
// LOTS OF STUFF SO YOU CANT SEE file2 below.
// We can re-use data here as it was closed.
std::ofstream file2("Data");
// DO STUFF
}
There is no reason to ever write a loop that is known, at compile time, to execute exactly once.
Doing so, in order to pretend that goto is written as break, is abusive.
EDIT:
I've just realised that my assertion about compile-time knowledge is false: I suppose you might do something complicated with conditional #defines that might mean that, at compile time for one build configuration, it is known to execute once, but for a different build configuration, it is executed multiple times.
#ifdef SOMETHING
#define CONDITION (--x)
#else
#define CONDITION 0
#endif
...
int x = 5
do{
...
} while(CONDITION)
However, the spirit of my assertion still stands.
It can be used to implement a behavior similar to goto statement, or say jump behavior!
See this:
do
{
if (doSomething() != 0) break; //jump
if (doSomethingElse() != 0) break; //jump
...
if (doSomethingElseNew() != 0) break; //jump
} while(false);
//if any of the break encountered, execution can continue from here, just after the do-while block!
// statement1
// statement2
// statement3
// so on
Taken from here: Are do-while-false loops common?