configuring gdb to change the display of objects - c++

In GDB, objects typically display with lots of tripe due to included template objects.
There's a lot of useless std::char_traits ...
Is there a way to filter this stuff out? Basically, I'd like to know if I can configure .gdbinit to display the text only for a std::string, and perhaps the first few elements for a vector.
Alternatively, is there some sort of macro I can write to let me print out just a particular field of an object instead of writing by hand
For a string, I can write:
p s.c_str()
but I'll get a seg fault if it's NULL.
I'd like enough logic to ignore that but don't know that gdb has any facility for it?

Yes, there are such things about! It's a bit limited but you can do it.
Look here and also here.

Related

Setting a Breakpoint in GDB

I have a function that returns a pointer:
static void *find_fit(size_t asize);
I would like to set a breakpoint in gdb, but when I type this function name, I get one of these errors:
break *find_fit
Function "*find_fit" not defined
or
break find_fit
Function "find_fit" not defined
I can easily set break point on a function that returns something other than a pointer, but when the function does return a pointer, gdb doesn't seem to want to break on it.
Anybody see what is going on? Thanks!
It sounds like for some reason, gdb isn't handling C++ name mangling correctly. Normally you don't have to touch anything for this to work. You can try show language. Typically it's set to auto. You can also try manually setting it with set language c++.
To test, you can just type
b 'find<tab>
(that's the tab character, not the characters "<tab>") and it should try to autocomplete the name of the function for you. In C++ you need the argument types to know the function, but that doesn't 100% fit with what you're seeing because if you give gdb a function name without arguments, it'll usually do the right thing or prompt you for which version of a function you want. You aren't seeing either of those.

let the user use a function in c++ [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
Dynamic source code in C++
is it possible to let the user type in a function and then run that function without using a lot of if's or a huge switch?
It is not possible to execute arbitrary c++ code in your program, since you than need a c++ compiler inside your program. But you could try to embed Python to your program. Boost python makes this relatively easy. The user can than write a python function that is executed and can interact with the classes and functions of your program. You need to make your functions explicitely visible to python.
What ever a user types in will be text, or a string. The only way I know to have it get mapped to a function is to use if/else or switch statements. That or the cringe inducing option of mapping each of your functions to a UI widget.
The end of the story, is it's your code. You have to write, and live with it. Just be careful, your program may be wildly successful, and you may not write code anymore, and then someone else will have to maintain your code. So be nice to the maintenance programmer who may follow you, and write code that isn't too tricky to figure out.
I assume you want something like eval from php.
You can try to play with command design pattern, but I doubt it will be an easy task. Basically you need to write simple C++ interpreter.
What type of function do you mean? A C++ function? If so, then you will have to either (1)interpret it or (2)compile and execute it. Interpretation would be the more likely choice here. I'm not sure if there are libraries out there already to do this but I'd assume there are.
If you don't like mega-if's or huge switches, you may be SoL on any solution for anything ever, but then again there is seldom one perfect way to do things. Consider looking in to various logic structures and algorithms to see how to do something that would normally be the job of a 23-case switch could be done another way. Like I said initially, however, sometimes you really do just need a million nested if's to do what you want to.
No, in C++ this is not possible. C++ is a compiled language. When the program runs, the compiler doesn't need to be accessible, or even installed on the machine that runs the program.
If you want to do this in C++, you need to write your own interpreter that parses whatever the user enters.
Here is my best idea, but it is a tad memory intensive.
First, create a class, lets call it MyFuncPtr to store a union of several different types of pointers to functions and an integer to tell which type it is. Overload the () operator to call the function stored with a variable length argument list. Make sure to include some sort of run-time argument checking.
Finally create a map of strings to MyFuncPtrs. Store your functions in this map along with their names. Then all you need to do is feed the name into the [] command to get a function that can be easily called. Templates could probably be used to aid in the making of MyFuncPtr instances.
This would be the easiest if it were plain C functions and no name mangling is performed on the symbols (use extern "C" { ... })
With some platform-specific code you can get the address of a function by its name. Then you cast the address as a function pointer which you can use to call the function.
On windows you must be using GetProcAddress and dlsym on Posix compliant platforms.

A Good Way to Store C++ CLI Arguments? (W/O using libraries)

So, I'm writting a CLI application in C++ which will accept a bunch of arguments.
The syntax is pretty typical, -tag arg1 arg2 -tag2 arg1 ...
Right now, I take the char** argv and parse them into an
std::map< std::string, std::list<**std::string** > > >
The key is the tag, and the list holds each token behind that tag but before the next one. I don't want to store my args as just std::strings; but I need to make it more interactive.
By interactive, I mean when a user types './myprog -help' a list of all available commands comes up with descriptions.
Currently, my class to facilitate this is:
class Argument
{
public:
Argument(std::string flag, std::string desc);
std::string getFlag();
std::string getDesc();
std:;list<std::string> > getArgs();
void setArgs(std::list<std::string> > args);
bool validSyntax()=0;
std::string getSyntaxErrorDesc()=0;
};
The std::map structure is in a class ProgramCommands which goes about handling the these Arguments.
Now that the problem description is over, my 4 questions are:
How do I give the rest of the program access to the data in ProgramCommands?
I Don't want to make a singleton, at all; and I'd prefer to not have to pass ProgramCommands as an arg to almost every function in the program.
Do you have better ideas about storing how I'm doing this?
How best can I add arguments to the program, without hardcoding them into the ProgramCommands, or main?
std::string only allows for 1 line descriptions, does anyone have an elegant solution to this besides using a list of strings or boost?
EDIT
I don't really want to use libraries because this is a school project (sniffing & interpreting packets). I could, if I wanted to, but I'd rather not.
Your choices on storing the command line arguments are either: Make them a global or pass them around to the functions that need them. Which way is best depends on the sorts of options you have.
If MANY places in your program need the options (for instance a 'verbose' option), then I'd just make the structure a global and get on with my life. It doesn't need to be a singleton (you'll still only have one of them, but that's OK).
If you only need the options at startup time (i.e. # of threads to start initially or port # to connect on), then you can keep the parsing local to 'main' and just pass the parameters needed to the appropriate functions.
I tend to just parse options with the venerable getopt library (yes, that's a leftover from C - and it works just fine) and I stuff the option info (flags, values) into a global structure or a series of global variables. I give usage instructions by having a function 'print_usage' that just prints out the basic usage info as a single block of text. I find it works, it's quick, it's simple, and it gets the job done.
I dont understand your objection to using a singleton to - this is the sort of thing they are made for. If you want them accessible to every object but not pass them as arguments or use a singlton - there are only a couple of tricks I can think of:
-put the parsed arguments them into shared memory and then read them from every function that needs them
-write the parsed arguments out to a binary file and then read them from every function that needs them
-global variables
None of these solutions are nearly as elegant as a singleton, are MUCH more labor intensive and are well... sort of silly compared to a singleton... why hamstring yourself?

isDefined function?

In C++ is there any function that returns "true" when the variable is defined or false in vice versa. Something like this:
bool isDefined(string varName)
{
if (a variable called "varName" is defined)
return true;
else
return false;
}
C++ is not a dynamic language. Which means, that the answer is no. You know this at compile time, not runtime.
There is no such a thing in runtime as it doesn't make sense in a non-dynamic language as C++.
However you can use it inside a sizeof to test if it exists on compile time without side-effects.
(void)sizeof(variable);
That will stop compilation if var doesn't exist.
As already stated, the C++ runtime system does not support the querying of whether or not a variable is declared or not. In general a C++ binary doesn't contain information on variable symbols or their mappings to their location. Technically, this information would be available in a binary compiled with debugging information, and you could certainly query the debugging information to see if a variable name is present at a given location in code, but it would be a dirty hack at best (If you're curious to see what it might look at, I posted a terrible snippet # Call a function named in a string variable in C which calls a C function by a string using the DWARF debugging information. Doing something like this is not advised)
Microsoft has two extensions to C++ named: __if_exists and __if_not_exists. They can be useful in some cases, but they don't take string arguments.
If you really need such a functionality you can add all your variables to a set and then query that set for variable existance.
Already mentioned that C++ doesn't provide such facility.
On the other hand there are cases where the OS implement mechanisms close to isDefined(),
like the GetProcAddress Function, on Windows.
No. It's not like you have a runtime system around C++ which keeps remembers variables with names in some sort of table (meta data) and lets you access a variable through a dynamically generated string. If you want this, you have to build it yourself, for example using a std::map that maps strings to some objects.
Some compile-time mechanism would fit into the language. But I don't think that it would be any useful.
In order to achieve this first you need to implement a dynamic variable handling system, or at least find some on the internet. As previously mentioned the C++ is designed to be a native language so there are no built-in facilities to do this.
What I can suggest for the most easy solution to create a std::map with string keys storing global variables of interest with a boost::any, wxVariant or something similar, and store your variables in this map. You can make your life a bit easier with a little preprocessor directive to define a variables by their name, so you don't need to retype the name of the variable twice. Also, to make life easier I suggest to create a little inline function which access this variable map, and checks if the given string key is contained by the map.
There are implementation such a functionality in many places, the runtime property handling systems are available in different fashion, but if you need just this functionality I suggest to implement by yourself, because most of these solutions are quite general what you probably don't need.
You can make such function, but it wouldn't operate strings. You would have to send variable name. Such a function would try to add 0 to the variable. If it doesn't exists, an error would occur, so you might want to try to make exception handling with try...throw...catch . But because I'm on the phone, I don't know if this wouldn't throw an error anyways when trying to send non-existing variable to the function...

Why can't I index a std::vector in the immediate window?

So, I have a vector
std::vector<std::string> lines.
I fill this vector up, and can access it like
std::string temp = lines[0];
However, in the immediate window, both
lines[0] - error:overloaded operator not found
and
lines.at(0) - error:symbol is ambiguous
don't work at all. Is there a trick to using the immediate window with c++. I'm mostly coming from a C# background, where everything works nicely (and I have intellisense in the Immediate Window). I wasn't expecting C++ to be great, but I figured it would work for things besides ints. Can anyone tell me what I'm doing wrong? Thanks.
EDIT: I should be clear, nothing really works in the immediate window, this is just a simplified example
EDIT: I'm in debug mode
The immediate and watch windows don't support overloaded operators. There is some support in there for printing standard containers as a whole in a sensible fashion (see, e.g., http://www.virtualdub.org/blog/pivot/entry.php?id=120), but this doesn't extend to being able to use operator[] on them.
Hopefully this will be improved in later revisions of the debugger, but for now, to look at the i'th element of a vector, try lines._Myfirst[i].
(_Myfirst, in the standard libraries that come with VC++, happens to be the member variable in a std::vector that points to the first element of the sequence. So this is just examining a vector as if it were any other object. To work this out, I had to look at the headers... not very convenient, but hopefully this will help you. You can probably do something similar with the other containers, but you'll have to look in the headers to work out how.)
(By the way, if you've been working in C#, the C++ debugger will probably seem by comparison a bit less slick in general, and this is just one example of that. I get the impression there's been much more work put into the CLR side.)
In nowaday's Visual Studio versions (e.g. 2013/2015) _Myfirst member variable does no longer exist for a std::vector variable. Use _C_begin instead - means for the given example use e.g. lines._C_begin[i].