This is my test program:
#include <iostream>
#include <atomic>
std::atomic<int> Counter = 200;
int main()
{
if(Counter > 0)
std::cout << "Hello World!\n";
}
I'm setting a breakpoint to the if(Counter > 0), and when it is hit I'm adding Counter to the watch window:
As you can see, the "Edit Value" entry is greyed out and it's impossible to change the value in the debugger. Replacing the variable definition with int Counter = 200; makes it editable in the debugger, but I lose the associated memory ordering semantics which I need.
Is there a way to create a counter with at least a release-consume ordering which I would be able to manipulate via the debugger?
Yes add the following to your watch window: Counter._Storage._Value
Related
Suppose I have a complex C++ application that I need to debug with a lot of variables. I wanna avoid using std::cout and printf approaches (below there's an explaination why).
In order to explain my issue, I wrote a minimal example using chrono (This program calculates fps of its while cycle over time and increment i_times counter until it reaches 10k):
#include <chrono>
using chrono_hclock = std::chrono::high_resolution_clock;
int main(int argc, char** argv){
bool is_running = true;
float fps;
int i_times=0;
chrono_hclock::time_point start;
chrono_hclock::time_point end;
while(is_running){
start = chrono_hclock::now();
// Some code execution
end = chrono_hclock::now();
fps=(float)1e9/(float)std::chrono::duration_cast<std::chrono::nanoseconds>(end-start).count());
if(++i_times==10000) is_running=false;
}
return 0;
}
I would like to debug this program and watch for fps and i_times variables continuosly over time, without stopping execution.
Of course I can simply use std::cout, printf or other means to output variables values redirecting them to stdout or a file while debugging and those are OK for simple types, but I have multiple variables which data type are struct-based and it would be creepy, time expensive and code bloating to write instructions to print each one of them. Also my application is a realtime video/audio H.264 encoder streaming with RTSP protocol and stopping at breakpoints means visualizing artifacts in my other decoder application because the encoder can't keep up with the decoder (because the encoder hit a breakpoint).
How can I solve this issue?
Thanks and regards!
The IDE I'm currently using for developing is Visual Studio 2019 Community.
I'm using the Local Windows Debugger.
I'm open to using alternative open source IDEs like VSCode or alternative debugging methods to solve this problem and/or to not be confinated into using a specific IDE.
To watch for specific multiple variables in VS I use the built-in Watch Window. While debugging with LWD, I add manually variables by right-clicking them in my source code and click Add Watch. Then those are showed in the Watch Window (Debug-Windows-Watch-Watch 1):
However I can only watch this window contents once I hit a breakpoint I set inside the while cycle, thus blocking execution, so that doesn't solve my issue.
You can use nonblocking breakpoint. First add the breakpoint. Then click on breakpoint settings or right click and select action.
Now you add a message like any string that is suggestive for you. And in brackets include the values to show, for instance
value of y is {y} and value of x is {x}
In the image is shown the value of i when it hits the breakpoint. Check the "Continue code execution" so breakpoint will not block execution. The shape of your breakpoint will change to red diagonal square. You can add also specific conditions if you click the Conditions checkbox.
Now while debugging all these debug messages will be shown in the output window:
In the above image it is showing the following message:
the value of i is {i}
By checking the "Conditions" you can add specific conditions, for instance i%100==0 and it will show the message only if i is divisible by 100.
This time your breakpoint will be marked with a + sign, meaning it has condition. Now while debugging there will be shown the i only when divisible by 100, so you can restrict the output to some more meaningful cases
The strict answer is "no" but...
I think I understand what you're trying to accomplish. This could be done by dumping the watched variables into to shared memory which is read by 2nd process. A watch and a break point in the 2nd would allow you to see the values in Visual Studio without interrupting the original application.
A few caveats:
UAC must be admin on both sides to open the memory handle
This wouldn't work with pointers as the 2nd program only has access to the shared memory
Windows anti-virus went nuts for the first few times I
ran this but eventually calmed down
Worker application:
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#include <windows.h>
#include <chrono>
#include <thread>
PCWSTR SHARED_MEMORY_NAME = L"Global\\WatchMemory";
struct watch_collection // Container for everything we want to watch
{
int i;
int j;
int k;
};
using chrono_hclock = std::chrono::high_resolution_clock;
int main(int argc, char** argv)
{
bool is_running = true;
float fps;
int i_times = 0;
chrono_hclock::time_point start;
chrono_hclock::time_point end;
HANDLE map_file;
void* shared_buffer;
// Set up the shared memory space
map_file = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(watch_collection), SHARED_MEMORY_NAME);
if (map_file == NULL)
{
return 1; // Didn't work, bail. Check UAC level!
}
shared_buffer = MapViewOfFile(map_file, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(watch_collection));
if (shared_buffer == NULL)
{
CloseHandle(map_file); // Didn't work, clean up the file handle and bail.
return 1;
}
// Do some stuff
while (is_running) {
start = chrono_hclock::now();
for (int i = 0; i < 10000; i++)
{
for (int j = 0; j < 10000; j++)
{
for (int k = 0; k < 10000; k++) {
watch_collection watches { i = i, j = j, k = k };
CopyMemory(shared_buffer, (void*)&watches, (sizeof(watch_collection))); // Copy the watches to the shared memory space
// Do more things...
}
}
}
end = chrono_hclock::now();
fps = (float)1e9 / (float)std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
if (++i_times == 1000000) is_running = false;
}
// Clean up the shared memory buffer and handle
UnmapViewOfFile(shared_buffer);
CloseHandle(map_file);
return 0;
}
Watcher application:
#include <windows.h>
#include <stdio.h>
#include <conio.h>
#include <tchar.h>
#pragma comment(lib, "user32.lib")
PCWSTR SHARED_MEMORY_NAME = L"Global\\WatchMemory";
struct watch_collection // Container for everything we want to watch
{
int i;
int j;
int k;
};
int main()
{
HANDLE map_file;
void* shared_buffer;
bool is_running = true;
watch_collection watches; // Put a watch on watches
// Connect to the shared memory
map_file = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, SHARED_MEMORY_NAME);
if (map_file == NULL)
{
return 1; // Couldn't open the handle, bail. Check UAC level!
}
shared_buffer = MapViewOfFile(map_file, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(watch_collection));
if (shared_buffer == NULL)
{
CloseHandle(map_file);
return 1;
}
// Loop forever
while (is_running)
{
CopyMemory((void*)&watches, shared_buffer, (sizeof(watch_collection)));
} // Breakpoint here
UnmapViewOfFile(shared_buffer);
CloseHandle(map_file);
return 0;
}
I'm currently new to programming and don't know, how to let the program process while the loading bar is running.
I wanted to display the loading bar and check, wether the program is finished processing. If not, then the processing bar should simply begin to fill again.
My code now is just showing the loading bar once and begins to process after that. This is pretty useless.
I researched on Google and here on stack overflow, but i only got the loading bar from that, not the useful integration in my program.
I just need a simple way to check, wether there would be an output besides the loading bar and i need to run the rest of the program at the same time as the loading bar, just to save time.
#include <iostream>
#include <windows.h>
#include <unistd.h>
#include <string>
#include <thread>
using namespace std;
static void loading(){
system("Color 0A");
cout<<"\t\n\n";
char a=177, b=219;
cout<<"\t";
for (int i=0;i<=50;i++)
cout<<a;
cout<<"\r";
cout<<"\t";
for (int i=0;i<=50;i++){
cout<<b;
for (int j=0;j<=2e7;j++);
}
cout << "\n\n";
}
int main(){
//ProjectEuler Problem___
loading();
int j=0;
do{
j++;
}while(j<=1e9); //just an example to see when it is processing
cout << "hi" << endl;
return 0;
}
I'm grateful for any help.
The typical pattern you're looking for would look something like:
void do_expensive_work(std::atomic<bool>& done) {
... something expensive goes here...
done = true;
}
int main() {
std::atomic<bool> done = false;
auto t = std::thread(do_expensive_work, std::ref(done));
while (!done) {
... update your progress bar ...
... sleep a bit ...
}
t.join();
return 0;
}
The specifics of how you communicate the result of your computation back to the calling thread etc are up to you. Similarly, you could in theory use a global atomic for the done status, or wrap up the computation in a class that keeps track of state and manages the execution of the thread. Code above is greatly simplified but gives a general pattern.
My application keeps closing when debugging. I'm not able to view what the "results" are since it goes too fast.
I've been looking at many different forums and topics and all the solutions given just wont apply. I've tried different commands before returns 0; etc and also changing an option in the project.
I'm just starting and trying to learn from the c++ primer but this is frustrating me already :).
Following is my code, please help!
#include <iostream>
int main ()
{
int sum = 0, val = 1;
while (val <= 10) {
sum +=val;
++ val;
}
std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;
Console.Read();
return 0;
}
Don't do Console.Read();, do std::cin.get();.
Try this:
#include <iostream>
int main ()
{
int sum = 0, val = 1;
while (val <= 10) {
sum +=val;
++ val;
}
std::cout << "Sum of 1 to 10 inclusive is "
<< sum << std::endl;
std::cin.get(); // hackish but better than system("PAUSE");
return 0;
}
Assuming that you are using Visual Studio:
Debug builds will run until they hit a breakpoint or until the program finishes (which ever comes first). If the program finishes, the console closes. Place a break point on the line containing return 0; and your console will stay open until you click Continue.
Release builds will run until the program finishes. If the program finishes, you will be prompted to Press any key to continue. . . and the console will stay open.
If you are not setting breakpoints in such a small program, you are wasting your resources -- debug mode will impact the performance of the program.
Thus, you should build in Release mode and forget about using std::cin.get().
I have to do a demonstration of how the compiler produces a infinity-loop while optimizing a program.
I have to show it in C++ in Visual Studio 2010 and I think he best way to show it is with and without volatile.
I used the code from here http://msdn.microsoft.com/en-us/library/12a04hfd%28v=vs.80%29.aspx
and tried it with and without volatile(and compile with: /EHsc /O2)
But there is no infinity-loop.
I also change it like that :
// compile with: /EHsc /O2
#include <iostream>
#include <windows.h>
using namespace std;
//volatile bool Sentinel = true;
bool Sentinel = true;
int CriticalData = 0;
int round=0;
unsigned ThreadFunc1() {
while (Sentinel){
Sleep(10); // volatile spin lock
cout << "Critical Data = " << CriticalData << endl;
}
return 0;
}
unsigned ThreadFunc2() {
Sleep(2000);
CriticalData++;
Sentinel = false;
return 0;
}
int main() {
HANDLE hThread1, hThread2;
hThread1 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadFunc1, NULL, 0, NULL);
hThread2 = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)&ThreadFunc2, NULL, 0, NULL);
CloseHandle(hThread1);
CloseHandle(hThread2);
system("pause");
}
But no infinity-loop. Does someone have an idea?
The compiler does not know for sure what Sleep(int) and iostream.operator <<() can do with your global variables. It's possible (from its point of view), that they can change Sentinel variable, so compiler can't remove reading of Sentinel from the loop.
What's the problem here? The compiler may produce an infinite loop without volatile, but it doesn't have to. It's more likely to see an infinite loop when compiling with highest optimization level and turning debug info off.
int gIMightBeUseful = 1;
void foo()
{
int bar;
while(!bar){gIMightBeUseful++;}
}
Has a chance of infinite looping depending on optimization level. Or does it have to be thread interlock specific?
I have an issue with Eclipse Indigo complaining that methods of a class couldn't be resolved, but compiling anyway and working correctly (AFAIK). It's a very simple program. Here is Population.cpp:
#include <stdlib.h>
#include <iostream>
#include <time.h>
#include "Population.h"
Population::Population() {
// TODO Auto-generated constructor stub
}
Population::~Population() {
// TODO Auto-generated destructor stub
}
void Population::initializePop(int numBits, int N) {
srand((unsigned)time(0));
for(int i=0; i<N; i++) {
x[i] = (char*) calloc(numBits, sizeof(char));
for(int j=0; j<numBits; j++) {
if( rand() < 0.5 )
x[i][j] = 0;
else
x[i][j] = 1;
}
}
}
char** Population::getX() {
return x;
}
void Population::printStuff() {
std::cout << "Whatever";
}
Now, I build that code and everything is fine. In another project within Eclipse, I'm calling this code like this:
#include <typeinfo>
#include <string.h>
#include <iostream>
#include "cute.h"
#include "ide_listener.h"
#include "cute_runner.h"
#include "Population.cpp"
void testPopulationGeneration() {
Population* p = new Population;
int N = 10;
int bits = 4;
char** pop;
ASSERTM("Population variable improperly initialized", dynamic_cast<Population*>(p));
std::cout << p->printStuff();
std::cout << "Ok...";
p->initializePop(bits, N);
pop = p->getX();
ASSERTM("Pop not correct size.", sizeof(pop) == 10);
}
As you can see I'm also running the CUTE plugin for TDD in C++. It doesn't complain when I declare p as type Population and the first assertion passes. I'm somewhat new to C++, but I did make sure to add the project that Population.cpp is from to the include path for the test project.
It's not a huge deal as it's not affecting anything obvious to me, but it's still very annoying. I don't see a situation where it should do this.
Thanks for any help!
Try this:
In your project explorer window, right click on your project -> Index -> Rebuild
This could be an indexing issue related to external #include headers not found. Follow the steps below and see if it helps:
Go to each of your custom #include (e.g. "cute.h") and press
F3 (i.e. "Show declaration"); see if it's able to access that file
or not; if not copy those files on some notepad
If the file is not accessible, then locate it paths in your
directory structure; e.g. "cute.h" and "a.h" are located at,
"C://Eclipse/MyWork/Workspace/Project/include_1" and
"ide_listener.h" is located
at,"C://Eclipse/MyWork/Workspace/Project/include_2", then copy both
the folder paths on some notepad
Inside Eclipse go to Project -> Properties -> C/C++ General ->
Paths and Sybmols; you will see several tabs as Includes,
Sybmols, Library Paths ...
Click Library Paths -> Add -> Workspace... -> <locate the above
folder paths> and press OK
Let the indexer rebuild; now again follow the step (1); hopefully
the files should be accessible
For future safety for larger files, go to Window -> Preferences ->
C/C++ -> Editor -> Scalability -> "Enable scalability mode when
..." and set the number of lines to some big number such as
500000 and press "OK";
The last step is needed, because when your file grows in line number and if exceeds the above number then eclipse will stop showing definitions for some "scalability" reasons, even though it would have indexed.
sizeof(pointer) returns the size of the pointer (4 on 32-bit systems and 8 on 64-bit), not the size of what it points to! Save the dimensions in the class, and add a function to return them.
Also, in initializePop shouldn't you allocate the actual X array?
X = calloc(N, sizeof(char *));
Or rather, you should use new for allocation since you are using C++:
X = new char* [N];
and later:
X[i] = new char [numbits];
Not that i'm any expert at all but i just had a similar problem using.empty for whatever reason it will work if you change char to string minor change but resolved the issue on my program