Setting breakpoint on a class's member function in a file - gdb

(gdb) b breakpoints.cpp:X::X()
Can't find member of namespace, class, struct, or union named "breakpoints.cpp:X::X"
Hint: try 'breakpoints.cpp:X::X()<TAB> or 'breakpoints.cpp:X::X()<ESC-?>
(Note leading single quote.)
Make breakpoint pending on future shared library load? (y or [n]) n
on the following code:
#include <stdio.h>
#include <iostream>
class X
{
public:
X ()
{
std :: cout << "\nIn the default constructor";
}
X (int)
{
std :: cout << "\nIn the parameterized constructor";
}
~X () {}
};
int main (int argc, char *argv[])
{
X xObjA;
X xObjB (11);
while (--argc > 0)
{
printf("\n%s ", argv [argc]);
}
std :: cout << std :: endl << std :: endl;
}
File's name is: breakpoints.cpp
What's the point that I am missing?

That is the correct way to set a breakpoint.
You are either trying that on a wrong executable (put breakspoints.cpp in a directory and compile with g++ -g breakpoints.cpp and then use the gdb on the a.out executable), code that is different than posted and maybe having namespaces, or you stumbled on an old bug due to using an outdated gdb version.

Perhaps you need to define your breakpoints without the file name. The following works for me:
break FooNamespace::FooClass::doSomething()
I imagine this only works when the class is unique however, so it should be in a namespace.
Note
If there are multiple places where the breakpoint can be placed, I think gdb will try to place breakpoints on all of the places, so you will end up with something like the following:
Breakpoint 1 at 0x7fe62f8e744d: file src/FooClass.cpp, line 42. (2 locations)
(gdb) info break
Num Type Disp Enb Address What
1 breakpoint keep y <MULTIPLE>
1.1 y 0x00007fe62f8e744d in FooNamespace::FooClass::doSomething() at src/FooClass.cpp:42
1.2 y 0x00007fe62f8e7c5d in FooNamespace::FooClass::doSomething() at src/FooClass.cpp:42

You may need to specify the namespace if any defined for the class. If it other than the standard namespace std.
The file name is optional, if you are executing the correct binary.
You can verify if the symbol exists on the executable via. "nm -C" command, where -C handles name mangling for C++.
So to summarise with an Example:
If the namespace is "mySpace" and the class is "X" whose member is "Y",
then the breakpoint should be like the one below,
"(gdb) b mySpace::X::Y"

Related

C++ variable declaration inside function that is not called changes the normal application flow

I'm trying to use Pleora SDK for creating a application to load images from a thermal camera.
So my first attempt is to find available devices in the network, however I'm facing a weird behavior in C++ that I really have no reasonable explanation: the code flow jumps to somewere else than the main function on the declaration of "PvSystem lSystem" even when it is not being called.
To aid my explanation, here is the code:
#include <iostream>
#include <PvSystem.h>
#include <PvInterface.h>
#include <PvDevice.h>
int DeviceFinding()
{
PvSystem lSystem;
return 0;
}
int main()
{
std::cout << "Application start" << std::endl;
//DeviceFinding();
return 0;
}
This code, when run on Ubuntu 16.04 64bits with the following build line:
g++ weird.cpp -g3 -o WeirdTest -I/opt/pleora/ebus_sdk/Ubuntu-14.04-x86_64/include -L/opt/pleora/ebus_sdk/Ubuntu-14.04-x86_64/lib -lPvBase -lPvBuffer -lPvStream -lPvDevice -lPvGenICam
outputs:
Error: GENICAM_ROOT_V2_4 is not set.
However, if I comment the line with "PvSystem lSystem",
#include <iostream>
#include <PvSystem.h>
#include <PvInterface.h>
#include <PvDevice.h>
int DeviceFinding()
{
// PvSystem lSystem;
return 0;
}
int main()
{
std::cout << "Application start" << std::endl;
//DeviceFinding();
return 0;
}
the application prints what is expected:
Application start
I really have no idea of what is going on. Can someone help me understanding this?
Intializations of global variables are invoked before main starts.
I dont know the Pleora SDK, but a possible explanation of the pattern is that PvSystem references some global object that needs to be constructed (or a global variable initialized through some function) before main starts, the error occurs in that constructor.
When that global object or variable is not referenced anywhere (when you comment the line PvSystem lSystem;) the linker dropped that global object from the linking and no constructor or initializer was called. That is because the linker is allowed to drop unreferenced globals from a library.
On the other hand, when you activate that line, the linker instantiated the global object (or variable) because it is referenced somewhere in PvSystem, and it invoked its constructor (or initializer) before main. That initializer has detected some error in the environment so it exited the application or threw an exception.
Another possibility is, as in #SamVarshavchik 's comment, you have yourself in your code some constructors (for global objects) invoked before main and a bug in those constructors provoked an undefined behavior.

GDB incomplete type when having C++ virtual function

I have just noticed something weird, when I add the "virtual keyword" in my class (any function except the constructor), I can't display the content of my object in GDB. GDB says "incomplete type"
Here is the code :
//////////////// reco.h /////////////
#ifndef RECO_H
#define RECO_H
#include <iostream>
#include <string>
class reco {
public:
reco(float weight);
~reco(void);
float getWeight();
private:
float weight;
};
#endif
///////////////// reco.cpp /////////////
#include <iostream>
#include <string>
#include "reco.h"
using namespace std;
reco::reco(float weight) {
weight = weight;
}
reco::~reco(void) {
cout << "destructor reco" << endl;
}
float reco::getWeight() {
return weight;
}
////////////// main.cpp /////////////
#include <iostream>
#include <string>
#include "reco.h"
using namespace std;
int main() {
reco* s = new reco(5.0);
cout << s->getWeight() << endl;
delete s;
return 0;
}
Then with GDB :
gdb main.exe
breakpoint main.cpp:11 <---- (cout)
run
print *s
$1 = { weight = 5 }
And then, if I make one of the functions "virtual", and I retry to print my *s pointer with GDB, it says:
"incomplete type"
It looks like there is something happening with the VTABLE, as if the "virtual" keyword was hiding the implementation of my Reco class. I know that the compiler does late binding and then, the VTABLE lookup is done at runtime, but the program is already running while GDB is debugging it, right ?
The "set print vtbl" setting in "on".
If I use ptype s, I get the <incomplete type> message again.
If I examine the address with x/540f80, it says "cannot access memory"
I don't know why just adding this keyword makes my object's type incomplete ?
Thanks a lot for your help !
One last thing that I notice :
WITH VIRTUAL:
reco.cpp -> g0 and main.cpp -> g = incomplete type
reco.cpp -> g and main.cpp ->g = ok
WITHOUT VIRTUAL
reco.cpp -> g0 and main.cpp -> g = ok
reco.cpp -> g and main.cpp ->g = ok
reco.cpp -> g and main.cpp ->g = ok
Assuming by -> g you mean that you compile reco.cpp with the -g flag, yes do that, and don't do this:
g++ -c -g0 reco.cpp
What you've discovered that is that GCC can optimize the amount on debug info it must emit if it knows that you have a key method.
Without virtual, there is no key method, and GCC must emit redundant debug info into every compilation unit. That makes your object files larger (it should have little or no effect on the final executable), but allows you to debug even when only some of your object files are compiled with debug info.

Why is my non-recursive sqrt function recursive?

I have the following C++ test program called test.cpp:
#include <cmath>
#include <iostream>
double sqrt(double d) { return std::sqrt(d); }
int main()
{
std::cout << "sqrt(4): " << sqrt(4) << std::endl;
}
This is some pretty contrived code, and as you might have guessed I'm just trying to do an exercise out of Stroustrup. He declared double sqrt(double), and wants the reader to define it.
I compiled the above code using g++ 4.8 (from the MINGW release of Qt 5.1):
C:\Windows\Temp>g++ -o test.exe -g test.cpp
When I ran the resulting executable, Windows 7 said "test.exe has stopped working".
To see what went wrong, I ran test.exe in the GNU debugger. Debugger commands and output:
C:\Windows\Temp>gdb -q test.exe
Reading symbols from C:\Windows\Temp\test.exe...done.
(gdb) b main
Breakpoint 1 at 0x401625: file test.cpp, line 8.
(gdb) run
Starting program: C:\Windows\Temp\test.exe
[New Thread 12080.0x2ba0]
Breakpoint 1, main () at test.cpp:8
8 std::cout << "sqrt(4): " << sqrt(4) << std::endl;
(gdb) s
sqrt (d=4) at test.cpp:4
4 double sqrt(double d) { return std::sqrt(d); }
(gdb) s
sqrt (d=4) at test.cpp:4
4 double sqrt(double d) { return std::sqrt(d); }
(gdb) s
sqrt (d=4) at test.cpp:4
4 double sqrt(double d) { return std::sqrt(d); }
(gdb) s
sqrt (d=4) at test.cpp:4
4 double sqrt(double d) { return std::sqrt(d); }
(gdb) q
A debugging session is active.
Inferior 1 [process 12080] will be killed.
Quit anyway? (y or n) y
C:\Windows\Temp>
From the behavior and warning, I infer that std::sqrt must be calling sqrt from the global namespace -- which causes my function to be repeatedly invoked.
It would be easy enough to work around the unwanted recursion by changing the name of my sqrt function, or by putting it inside a namespace. But I would like to understand why std::sqrt is implemented in such a way that ::sqrt is called. I thought the whole point of the std namespace was to prevent name clashes with unqualified names in user code.
I took a peek at the source code for the GNU implementation of <cmath>. However, I lost the trail after following a few #includes in the chain. Maybe you can make more sense of it:
00052 #include <math.h>
00053
00054 // Get rid of those macros defined in <math.h> in lieu of real functions.
....
00076 #undef sqrt
....
00081 namespace std
00082 {
....
00393 using ::sqrt;
00394
00395 inline float
00396 sqrt(float __x)
00397 { return __builtin_sqrtf(__x); }
00398
00399 inline long double
00400 sqrt(long double __x)
00401 { return __builtin_sqrtl(__x); }
00402
00403 template<typename _Tp>
00404 inline typename __enable_if<double, __is_integer<_Tp>::_M_type>::_M_type
00405 sqrt(_Tp __x)
00406 { return __builtin_sqrt(__x); }
....
00437 }
Incidentally, this is not just a GNU puzzle. Compiling with the Visual C++ compiler instead of g++ yields the following warning:
C:\Windows\Temp>cl /nologo /EHsc test.cpp
test.cpp
c:\windows\temp\test.cpp(4) : warning C4717: 'sqrt' : recursive on all control
paths, function will cause runtime stack overflow
I guess that makes this a fair question to ask on StackOverflow. :)
Running the resulting executable leads to the expected outcome: "test.exe has stopped working".
The problem is that the functions inherited from the C standard library like, e.g., the <cmath> functions are somewhat funny beasts: they are made to look as if they live in namespace std but really they are extern "C" functions living in the global namespace. Basically calling std::sqrt(x) effectively calls ::sqrt(x) which happens to be the function you just defined!
I haven't checked what the C++ standard says about these names in the global namespace but I'd be fairly certain that it classifies them as reserved names. That is, you'd better not define ::sqrt in any shape or form. Define the function in a suitable namespace and you'll be fine.
OK, I checked. The relevant clause is 17.3.24 [defns.reserved.function]:
reserved function
a function, specified as part of the C++ standard library, that must be defined by the implementation [ Note: If a C++ program provides a definition for any reserved function, the results are undefined. —end note ]
... and 17.6.4.3.3 [extern.names] paragraph 3 and 4:
Each name from the Standard C library declared with external linkage is reserved to the implementation for use as a name with extern "C" linkage, both in namespace std and in the global namespace.
Each function signature from the Standard C library declared with external linkage is reserved to the implementation for use as a function signature with both extern "C" and extern "C++" linkage, or as a name of namespace scope in the global namespace.
17.6.4.3.3/2 Each global function signature declared with external linkage in a header is reserved to the implementation to designate that function signature with external linkage.
17.6.4.3.3/3 Each name from the Standard C library declared with external linkage is reserved to the implementation for use as a name with extern "C" linkage, both in namespace std and in the global namespace.
17.6.4.3.3/4 Each function signature from the Standard C library declared with external linkage is reserved to the implementation for use as a function signature with both extern "C" and extern "C++" linkage, or as a name of namespace scope in the global namespace.

From where does the compiler start reading

This is a small program :
#include <iostream>
using namespace std;
int main() {
f();
system("pause");
}
void f() {
static int x = 20 ;
class tester {
public :
tester() {
cout << x ;
}
} x1;
}
The error that i get here is :error C3861: 'f': identifier not found
If i place the function f above main I will get the desired output.
Why it is so ?
I was told that program execution begins at main. According to this the code should run in the first case also.
How does the compiler start reading the program?
The beginning of the compilation and the beginning of the execution of the program are two different things.
The execution starts from the main.
The compilation begins from the beginning of the file; the compiler don't "jump around" the file to find the needed pieces, but it reads the input in a linear fashion (I suspect that this related, among the other things, to the fact that the C++ grammar is really complicated).
When the compiler is at some point in parsing the file, it only knows what has been declared/defined up to that point1.
Because of this, function prototypes (and non-defining declarations in general) have been invented: the prototypes of all the functions defined in the file are put at the beginning of the file, typically after the #include directives or in a separated include file. The prototypes tell to the compiler that such functions will be defined later, and what is the function signature (i.e. name, parameters, return value).
The prototype is made as a normal function, but without the body, which is replaced by a semicolon2. For example, in your code you would write
void f();
before the main.
IIRC there are some relaxations to this rule that allow the compiler to "wait" for some declarations to make some template magic work, but this is not relevant here.
In a prototype is also common not to write the names of the parameters, leaving just their type (this can be done also in function definitions, but it doesn't make much sense there unless you have a formal parameter you don't use). Still, I prefer to leave the parameter names there as a form of documentation.
I was told that program execution begins at main.
And that's exactly the point.
The compiler starts from main, and then sees a call to f(), which it has not encountered so far (as it is defined afterwards), so it does not know what to do with it.
If you want to define f after main you can place a function prototype before, such as
#include <iostream>
using namespace std;
void f(); // <--- This tells the compiler that a function name f will be defined
int main() {
f();
system("pause");
}
void f() {
static int x = 20 ;
class tester {
public :
tester() {
cout << x ;
}
} x1;
}
To be able to call a function it must have been declared at some earlier point in the code. This is just a rule of the language designed to help compilers.
You can declare the function earlier with e.g.
void f();
...and then define it after main as you have done.
The compiler starts at the top and reads down to the bottom.
you'll need to have something like:
#include <iostream>
using namespace std;
void f();
int main() {
f();
system("pause");
}
void f() {
static int x = 20 ;
class tester {
public :
tester() {
cout << x ;
}
} x1;
}
No, the compiler needs to see at least a declaration of f() before it is used. A c(++) code file is a simple text file and must be read from begin to end by the compiler.
During the compilation process, when the compiler is evaluating main() it needs to know what f() is in advance to be able to generate the correct assembly code to call this function. That's why you need to put it before main() in this case.
As an alternative you can declare the prototype of f() before main() so the compiler knows it's a local function declared somewhere else on your file:
void f(); // prototype
int main()
{
// .. code ..
}
void f() // implementation of f()
{
// .. code ..
}

Call main() itself in c++?

#include <iostream>
#include <cstdlib>
int main() {
cout << "!!!Hello World!!!" << endl;
system("pause");
return main();
}
The above works, but it hardcoded the main() function. Is there a magic variable or macro to get the current running function?
Is it allowed in "C++"? No.
In practice, can you call main()? Yes.
Whatever the C++ Standard says, that doesn't stop the Linux g++ compiler from compiling code with main() in main().
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
int y = rand() % 10; // returns 3, then 6, then 7
cout << "y = " << y << endl;
return (y == 7) ? 0 : main();
}
Which lets us do:
> g++ g.cpp; ./a.out
y = 3
y = 6
y = 7
Looking in to the assembly, we see that main is called just like any other function would be:
main:
...
cmpl $7, -12(%rbp)
je .L7
call main
...
.L7:
...
leave
ret
Not that this behavior is guaranteed, but it looks like g++ doesn't seem to really care about the standard, apart from this sarcastic warning with -pedantic
g.cpp:8: error: ISO C++ forbids taking address of function '::main'
The C++ Standard says that you may not call main() from your own code. As for getting the name of the current function, you could use the __FUNCTION__ macro, but once again this is not standard:
#include <iostream>
using namespace std;
void foo() {
cout << __FUNCTION__ << endl;
}
int main() {
foo();
}
should print "foo" or something similar if __FUNCTION__ is supported.
If a specific implementation allows this, it is not behaving correctly(a). The standard state quite explicitly in C++14, 3.6.1 Main function /3:
The function main shall not be used within a program.
(a) Keep in mind that many implementations follow some parts of the standard loosely, preferring power over strictness. That can have the unfortunate side effect that your code may not be portable to other compilers or even other versions of the same compiler.
Many implementations will also allow you to take the stricter view, such as using g++ -std=c++11 -Werror=pedantic which catches the particular issue bought up in this question, as well as quite a few others. It is that "mode" of translation that allows implementations to claim to be compliant with the standard, as per 1.4 Implementation compliance:
If a program contains a violation of any diagnosable rule ..., a conforming implementation shall issue at least one diagnostic message.
You'll see it's still quite possible to allow the code to compile and run in that case, since "diagnostic message" can mean a warning rather than an error.
Generally, no. For now it will be enough for you to know that the compiler needs to know the exact function you're calling at the compile time. You cannot do magic like, let's say
func = "my_function";
func();
if the called function name will change during runtime. (There are exceptions and ways around that, but you don't need that).
Don't think about that as a case of hard-coding: it is not. If you need to call the function, then you just write its name, and don't try to abstract it, or something.
Also, now would be a nice way to learn about the while loop, infinite loops and write without the function calls at all, e.g
int main()
{
while (1) {
cout << "!!!Hello World!!!" << endl; // prints !!!Hello World!!!
system("pause");
}
}