Is there a way to control flow of C++ code from outside? - c++11

I have a sample code :
#include<iostream>
main()
{
int i = 10; //Line 1
std::cout<<" i : "<<i; //Line 2
}
I want to somehow insert another statement (lets say one more std::cout) between Line-1 and Line 2.
Direct way is to change the source code and add required line. But for my source code compilation takes lot of time, so i can't afford to change the code frequently. So i want an automatic way such that i will be able to execute any statement in any function from outside so that upon hitting that function it execute my newly given statement.
I am not sure if this is possible or not. But any direction in writing the original code in such a way that my requirement can be fulfilled would be helpful.
[for debugging prupose]

If you want new C++ code to be executed, it must first be compiled. I don't think you can avoid that. You can however try to reduce how long the compilation takes, through various practices such as using header guards and being selective with headers.

There is a lot you can do in gdb to modify the behaviour of your program when it hits a nonstop breakpoint. The print command can also be used to change values, eg print i=0 actually sets i to zero.
Just remember that all these changes and hacks need to be ported back into the source code and tested again! I have lost many excellent edits over the years doing inline hacks in running code, and then exiting without reviewing the changes.

Related

How does an interpreter run code?

Reading all the compiled vs interpreted articles it seems like compiled means the machine will run the compiled code directly whereas interpreted, the interpreter will run the code. But how does the interpreter run the code if it's on a machine? Doesn't it still end up having to convert what it's interpreting into machine code and STILL having the machine run it? At the end of the day, everything has to end up being machine code in order for the machine to run it right? It seems like interpreted just means that it's running through the language one line at a time whereas compiled means going thru it all at once. After that, it's pretty much the same right?
Related: How programs written in interpreted languages are executed if they are never translated into machine language?
No, it doesn't need to convert it to a machine code. The instructions merely provide instructions to the interpreter itself, which the interpreter then executes itself.
Consider a really dumb "language" that consists of the following instructions:
add [number]
subtract [number]
divide [number]
multiply [number]
We could implement an "interpreter" like this (written in C#):
public static void ExecuteStatements(List<string> instructions)
{
int result = 0;
foreach (string instruction in instructions)
{
string[] action = instruction.Split(' ');
int number = int.Parse(action[1]);
switch (action[0].Trim().ToLower())
{
case "add":
result += number;
break;
case "subtract":
result -= number;
break;
case "divide":
result /= number;
break;
case "multiply":
result *= number;
break;
}
}
Console.WriteLine("Result: " + result);
}
The ExecuteStatements method will be compiled to machine code. Separately, we have a text file like this:
add 1
subtract 1
add 10
multiply 50
divide 5
The result will be 100. The strings are never actually compiled to anything - they just tell the interpreter what actions to take.
Obviously, this "language" isn't even close to Turing-complete, but the point is that at no point are we somehow "translating" this into machine code - the "interpreter" just takes whatever action is specified.
I actually wrote an interpreter once as part of a Test Automation framework. When someone did a call against the API, we would intercept the call, use reflection on it to determine what the call was and what the parameters were, and serialize the reflection metadata to JSON. We then later deserialized the JSON and used reflection to call whatever methods had been run before with the same parameters. The engine consumed JSON, not machine code, and used that to figure out what calls it should perform; at no point did it create or need any machine code. The critical thing was that, assuming that it had been given a valid script, the engine "knew" how to perform all of the specified actions itself, so it never needed to "offload" any of the instructions to the machine itself.
Here's the key insight: the interpreted code itself is quite literally doing nothing - all it's doing is feeding the interpreter which actions it needs to take. The interpreter already "knows" how to take all of the actions you can perform in the interpreted language, so no additional machine code is required.
As an analogy, think of the code you're interpreting as a recipe and the interpreter as a cook. The recipe specifies actions like "add 1 cup of flour and mix." The cook knows how to follow whatever directions he finds in the recipe and he performs them himself. Strictly speaking, the recipe isn't actually doing anything - it's just sitting there for the cook to read so that the cook can know what actions to take. There's no need for the recipe to actually be a cook in order for the recipe to be completed - it just needs someone who knows how to follow its directions.
TL;DR You don't need to "translate" it into machine code - you just need to have enough information for your interpreter to know what actions to take. A good interpreter already "knows" how to take whatever actions the language could implement, so there's no need to create any additional machine code.

VB6 - Set Debug Mode via Registry?

I have a VB6 application that I'm trying to make log out differently. What I have is a flag in the registry (existing) which states if the application is set to Debug mode so that it would log out.
Within my code I then have lots of if statements checking if this is true. This means that there is a lot of processing time checking if a statement is true, which maybe not much really but as it does it so often it's an overhead I would like to reduce.
The code is full of statements like this
If isDebug = True Then
LogMessage("Log what is happening")
End If
So what I'm looking for is a better way to do this. I know I can set a debug mode within Project Properties -> Make, but this needs to be set prior to building the .exe and I want to be able to set this in production via the registry key.
Consider using a command line argument to set debug mode. I used to do this.
Dim sCommandLine() As String
sCommandLine = Split(Command$)
For I = 0 To UBound(sCommandLine)
' do something with each arg
Next I
You can also persist command line args inside the IDE, so you always have them when debugging. When running outside of the IDE, make a shortcut to the compiled application with the arguments in it.
I do something almost identical to what you have in mind in a lot of my code. Add this:
Sub LogDebug(ByVal strMsg As String)
If (isDebug) Then
LogMessage(strMsg)
End If
End Sub
Then just call LogDebug in your main program body, or call LogMessage directly if it's something you always want to log, regardless of the debug flag.
I'm assuming isDebug is a boolean here. If it's a function call, you should just create a global flag that you set at the beginning of the code, and check that instead of looking at the registry over and over. I don't think checking a boolean is that much of a processing load, is it?
You want to call a function if a runtime flag is set. The only thing I can see that could be faster is:
If isDebug Then
LogMessage("Log what is happening")
End If
But I doubt that either would be the cause of performance problems. Most logging frameworks promote code like that and even put the flag/log level as a parameter to the function. Just be sure that you don't have other places where you needlessly compute a log message outside of the conditional statement.
You might evaluate why you need logging and if the logs produced are effective for that purpose.
If you are looking for a problem that can be trapped using VB error handling, consider a good error handling library like HuntERR31. With it you can choose to log only errors instead of the debug message you are now doing. Even if you don't use the library, the docs have a very good description of error handling in VB.
Another answer still:
Read your registry flag into your app so that it's a session based thing (i.e. when you close and restart the app the flag will be checked again - there's no point in checking the registry with every single test).
Then (as per Tom's post) assign the value to a global variable and test that - far faster than a function.
To speed up logging you may want to consider dimensioning a string buffer in your app and, once it has reached a specific size, fire it into your log file. Obviously there are certain problems with this approach, namely the volatility of the memory, but if you want performance over disk access I would recommend such an approach.
This would, of course, be a lot easier if you could show us some code for your logging process etc.

Applescript has a limit of the number of lines.

I am making an app with a TON of features. My problem is that applescript seems to have a cut-off point. After a certain number of lines, the script stopps working. It basically only works until the end. Once it gets to that point it stops. I have moved the code around to make sure that it is not an error within the code. Help?
I might be wrong, but I believe a long script is not a good way to put your code.
It's really hard to read, to debug or to maintain as one slight change in a part can have unexpected consequences at the other part of you file.
If your script is very long, I suggest you break your code in multiple parts.
First, you may use functions if some part of the code is reused several times.
Another benefit of the functions is that you can validate them separately from the rest of the execution code.
Besides, it makes your code easier to read.
on doWhatYouHaveTo(anArgument)
say "hello!"
end doWhatYouHaveTo
If the functions are used by different scripts, you may want to have your functions in a seperate library that you will call at need.
set cc to load script alias ((path to library folder as string) & "Scripts:Common:CommonLibrary.app")
cc's doWhatYouHaveTo(oneArgument)
At last, a thing that I sometimes do is calling a different script with some arguments, if a long code fits for slightly different purposes:
run script file {mainFileName} with parameters {oneWay}
This last trick has a great yet curious benefit : it can accelerate the execution time for a reason I never explained (and when I say accelerate, I say reduce execution time by 17 or so for the very same code).

Wisdom in FFTW doesn't import/export

I am using FFTW for FFTs, it's all working well but the optimisation takes a long time with the FFTW_PATIENT flag. However, according to the FFTW docs, I can improve on this by reusing wisdom between runs, which I can import and export to file. (I am using the floating point fftw routines, hence the fftwf_ prefix below instead of fftw_)
So, at the start of my main(), I have :
char wisdom_file[] = "optimise.fft";
fftwf_import_wisdom_from_filename(wisdom_file);
and at the end, I have:
fftwf_export_wisdom_to_filename(wisdom_file);
(I've also got error-checking to check the return is non-zero, omitted for simplicity above, so I know the files are reading and writing correctly)
After one run I get a file optimise.fft with what looks like ASCII wisdom. However, subsequent runs do not get any faster, and if I create my plans with the FFTW_WISDOM_ONLY flag, I get a null plan, showing that it doesn't see any wisdom there.
I am using 3 different FFTs (2 real to complex and 1 inverse complex to real), so have also tried import/export in each FFT, and to separate files, but that doesn't help.
I am using FFTW-3.3.3, I can see that FFTW-2 seemed to need more setting up to reuse wisdom, but the above seems sufficient now- what am I doing wrong?

is there a way to track the values of certain variables after the end of a program in visual studio?

i have found myself several times in the need of knowing the last values set to a range of variables that were in a certain portion of code, or method; maybe dispersed around the program.
does anyone know a way to select variables and know the last value set to them after the program ends running - in a windows maybe ?
There isn't anything I know of that will record every value ever assigned to every variable in your program in case you want to look at it later. It is possible with VS2010's historical debugging abilities to look at "values from the past" although I haven't used this yet, so I don't know if that ability extends "beyond death" of the process.
You may also be able to use tracepoints (VS2008 and later). These are like breakpoints, but instead of stopping execution they simply print information to the debug output. So you could add a tracepoint for a variable so that each time it is changed its value is reported (basically the same as printing the values out in your code, but you don't have to change your code to enable them, and can add them while your code is executing).
Two simple approaches that will work for pretty much any dev environment are:
Write the values to an application log each time they change, then read the last reported entries. If you realise you need 5 values from all around the program, simply printing them to the debug output will only take a few seconds to add to your program. (If you can't do this easily, then you're not encapsulating your data very well).
Put a breakpoint on the destructor of the class you're interested in, or at the start of the shutdown process just before you destroy the objects, or the last line of code in your program (for statics) (etc) and just use the debugger to drill down into the data.

Resources