So I just started teaching myself C++ and I have two newbie questions regarding the Hello World exercise.
#include <iostream>
using namespace std; [1]
int main()
{
cout << "Hello, World" << endl; [2]
return 0;
}
[1] Is this line of code necessary? If not, why? It worked without it but I found a source that used it and was wondering why was this used.
[2] On my first try I forgot to add endl and the code worked. When I went to check I realised this was missing so why did it still work anyway?
Really basic questions but I want to understand the basics well.
Many thanks in advance.
Is this line of code necessary? If not, why? It worked without it but I found a source that used it and was wondering why was this used.
Namespace
First of all you should have to understand what a namespace is.
That's an argument reference:
Namespace.
Pratically a namespace is like a container. You can keep different
symbol's names. In that way, in very large project, it is possible define two different symbols (e.g two functions) with the same name.
I try to give you a little example:
I can define two different functions foo with the same name. It possibile because I put them inside two different namespaces.
namespace my_ns1 {
void foo(int a) {
return a;
}
}
namespace my_ns2 {
void foo(int a) {
return a + 2;
}
}
When I want to call the first foo function the proper invokation
will be:
my_ns1::foo(10); // return 10
If i want to call the second foo function, then:
my_ns2::foo(10); // return 12
In a specific block I can specify the intent to use always a namespace
with the code:
using namespace my_ns1;
In that way there is no more need to specify the "full name" of the function.
The standard library keeps all its function in a proper namespace: std.
So when you want to use a function in the standard library you have to invoke it with something like:
std::function(...)
If you use the code
using namespace std;
At the begin of your file, you're just saying to "open" that namespace
and you can call all function without std::
The namespace is usefull in order to prevent name conflict.
[2] On my first try I forgot to add endl and the code worked. When I went to check I realised this was missing so why did it still work anyway?
Simply
std::endl
is a proper way to insert the '\n' character which means "an end of line".
Sorry for weird title. Limited to 150 chars so couldn't use proper sentences.
So let's say I've done the following to find out that something went wrong with my file stream:
std::ofstream ofs;
do_stuff_with(ofs);
// streams don't throw on error because C++ [edit: we can make them do so, but the .what()s aren't very user-friendly]
// so we have to check for failure manually
if(!ofs){
auto fail_code = errno; // threadsafe on Win/Linux
// but what goes here?
}
1) strerror:
Not threadsafe
2) strerror_s: Not in GCC? Or is it?
3) strerror_r: Not in Msvc? Or is it?
4) #ifdef/#define/etc: yuck, but may be the only choice
I did do some searching but I didn't find a "this will definitely work in a sensible yet slightly platform-dependent way" answer... That said, I feel like this is "obviously a duplicate question", but I can't find the original...
You can always throw your own exceptions using std::system_error:
#include <cerrno>
#include <fstream>
#include <iostream>
#include <system_error>
int main()
{
try
{
std::ofstream foo{"/root/bar.baz"};
foo << "bla" << std::endl;
foo.close();
if(!foo)
throw std::system_error{errno, std::generic_category()};
}
catch(const std::system_error& err)
{
std::cout << "Error: " << err.code() << " - " << err.what() << std::endl;
}
return 0;
}
This returns Error: generic:13 - Permission denied.
Since C++11, you can use the class std::error_code for that:
std::cout << std::error_code{errno, std::generic_category()}.message();
In fact you can even do it a little shorter than that:
std::cout << std::generic_category().message(errno);
Though I must say I find the first one a little more idiomatic.
As a sidenote, there is also std::system_category(), which seems to be largely equivalent to generic_category() on Unix but on Windows, it can be used to translate Windows API error codes such as returned by GetLastError() etc.
This is the same class that's also used within the std::system_error exception, but you don't need to create an instance of the exception if all you want to do is to get the error message.
This is the best I could come up with. It's the "yuck" answer, but at least you can put the "yuck" in a single function and hide it away in some cpp file somewhere. std::ios covers boost streams as well, of course.
Requires #ifdefs so it's a cheat. I believe Visual Studio #defines _WIN32 by default, so at least you don't have to set up that infrastructure per se.
void check_stream(std::ios & stream)
{
if (!stream){
char err[1024] = { 0 };
#ifdef _WIN32
strerror_s(err, errno);
#else
strerror_r(errno, err, 1024);
#endif
throw MyException(err);
}
}
My own solution makes me sad so hopefully a better one will come along. But time is finite, so just submit to the Dark Side, use something like this, and get on with your life. :P
try{
boost::filesystem::ifstream ifs("testfile");
check_stream(ifs);
}
catch (std::exception & e){
std::cout << e.what(); // "No such file or directory"
}
I would like to understand why my program crashes when I try to use the wsregex::compile of BOOST with the following string:
(?P<path>\b[a-z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*)?
(:)?
(?P<ip>(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b)
(;(?P<port>\d*))?
(:(?P<port>\b\d+\b):(?P<password>[\w]*))?
(:(?P<password>\b\d+\b))?
In regex buddy everything appears to be fine. I used the JGSoft flavor option on RegexBuddy.
I am validating the following:
c:\My Documents\Test\test.csv:1.12.12.13:111:admin
c:\My Documents\Test\test.csv:1.12.12.13:111
c:\My Documents\Test\test.csv:1.12.12.13;111
1.12.12.13:111
1.12.12.13;111
Can you guys help me. Thanks a lot.
This is neither a memory leak nor a crash as far as I can tell. Xpressive is throwing an exception because this is an invalid pattern. The following program:
#include <iostream>
#include <boost/xpressive/xpressive_dynamic.hpp>
namespace xpr = boost::xpressive;
int main()
{
const char pattern[] =
"(?P<path>\\b[a-z]:\\\\(?:[^\\\\/:*?\"<>|\\r\\n]+\\\\)*[^\\\\/:*?\"<>|\\r\\n]*)?"
"(:)?"
"(?P<ip>(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b)"
"(;(?P<port>\\d*))?"
"(:(?P<port>\\b\\d+\\b):(?P<password>[\\w]*))?"
"(:(?P<password>\\b\\d+\\b))?";
try
{
xpr::sregex rx = xpr::sregex::compile(pattern);
}
catch(xpr::regex_error const & e)
{
std::cout << e.what() << std::endl;
}
}
Outputs:
named mark already exists
Indeed, it does. This pattern uses "port" and "password" twice as the name of a capturing group. Xpressive doesn't like that. Just pick unique names for your captures and you should be fine.
I look at how we use Boost::Extension BOOST_EXTENSION_TYPE_MAP_FUNCTION macro.
For example like this:
BOOST_EXTENSION_TYPE_MAP_FUNCTION
{
std::map<std::string, boost::extensions::factory<service> > &factories(types.get());
factories["file_service"].set<file_service>();
}
BOOST_EXTENSION_TYPE_MAP_FUNCTION macro is defined in extension.hpp.
I wonder how this macro understands what is in Curly Brackets and how for example expand this macro to something that would cout anything like "Hello extended macro"?
Let me put my comment into an answer...
A macro is an instruction to the compiler (I use the collective term here) to substitute at that location the symbols defined as that macro, for example
#define FOO 1
int val = FOO; // at this point, FOO is replaced with 1
(p.s. please don't do this in C++)
Now, what is happening in your case is that there is a set of symbols (the signature of a function) defined as a macro, so all that happens is the compiler will substitute the macro with the symbols, and the end result would look (roughly) like this:
void boost_extension_exported_type_map_function(boost::extensions::type_map& types)
{
std::map<std::string, boost::extensions::factory<service> > &factories(types.get());
factories["file_service"].set<file_service>();
}
Which as you can see is a simple function. You can do this too (but don't unless you have a very good reason)
#define BOB void foo(std::string const& bar)
BOB
{
std::cout << "HEllo: " << bar << std::endl;
}
It simply allows a user to define their own implementation for that function... presumably somewhere else - it takes the address of that function and uses it via a pointer...
I am looking for a clever way to track function calls and returns.
I know I can use the debugger, but I would like a way to just have it print something out to the terminal when calling a function vs having to step through code.
I am thinking that I might be able to use the preprocessor, but I am not sure what would be the best way to go about this.
Or is there a way to use gdb to print out the information that would be useful, while not having to step through the code.
Most compilers allow you to inject an instrumentation function before and after the function call.
In MSVC they are _penter and _pexit. A nice article: http://www.drdobbs.com/184403601.
In GCC you would use the -finstrument-functions option, see the docs.
You can use debug libaries or map files to get more info.
A quite intrussive solution is using RAII to control the scope of the function. This will have a great impact in performance, but will be quite explicit in the logs without requiring the user to add instrumentation in all possible code paths that may leave the function:
class ScopeLogger {
public:
ScopeLogger( std::string const & msg ) : msg(msg)
{ std::cout << "Enter: " << msg << std::endl; }
~ScopeLogger()
{ std::cout << "Exit: " << msg << std::endl; }
std::string msg;
};
#if DEBUG
#define FUNCTION(x) ScopeLogger l_##x##_scope(x);
#endif
void foo( int value ) {
FUNCTION( __FUNCTION__ );
if ( value > 10 ) throw std::exception;
std::cout << "." << std::endl;
}
int main() {
foo(0); // Enter: foo\n.\nExit: foo
foo(100); // Enter: foo\nExit: foo
}
If the code is single threaded, you might even want to add a static variable with some indentation level to ScopedLogger without adding too much to the already heavy performance impact:
class ScopeLogger {
public:
ScopeLogger( std::string const & msg ) : msg(msg)
{ std::cout << std::string(indent++,' ') << "Enter: " << msg << std::endl; }
~ScopeLogger()
{ std::cout << std::string(--indent,' ') << "Exit: " << msg << std::endl; }
std::string msg;
static int indent;
};
int ScopeLogger::indent = 0;
Since you are using GCC, you can also use linker function wrapping.
Link-Time Replacement / Wrapping
– GCC option: -Wl,--wrap,function_name
Basically, you can take a function called "function_name()" and wrap it with a function called "__wrap_function_name()". You can access the original function by calling "__real_function_name()".
#define BEGIN_FUNC(X) printf("Function %s Entered",X)
#define END_FUNC(X) printf("Function %s End",X)
foo()
{
BEGIN_FUNC(__func__);
//Your code here
END_FUNC(__func__);
}
I think if you write a macro like above and use it for every function as described then you can get the logs on the terminal.
You may want to look at Valgrind's Callgrind which can track function calls into a pretty graph. It will show function calls, but not the parameter or return values.
Or is there a way to use gdb to print out the information that would be useful, while not having to step through the code
Yes. Set a breakpoint only at the functions that you actually care about. Use "continue" until you get to those functions or until your program crashes. Then use "backtrace" (or "bt") to get a stack trace.
If you need to automate it, you might take a look at TARGET_ASM_FUNCTION_END_PROLOGUE and TARGET_ASM_FUNCTION_BEGIN_EPILOGUE. These are compiler hooks that will let you specify pieces of assembly to be emitted along with the normal function prologue/epilogue -- in your case, you'd use them to emit a little assembly to log the entry/exit from the function in question. You could also look at FUNCTION_PROFILE and/or PROFILE_HOOK (e.g., at: http://gcc.gnu.org/onlinedocs/gccint/Function-Entry.html).
Below is an example illustrating the GCC side of the answer by Jonathan Fischoff.
Here we call external tool addr2line to print the location as functionName at /path/to/file.cpp:line instead of simply the address. I've tried using dladdr for this (as suggested in a comment to the answer linked above), but it returned only null pointers in dli_sname for me.
This approach of resolving the addresses has some drawbacks:
It's slow due to fork/execve/file read.
It needs exact file path to the binary containing the address, so the simple code below can't print symbols in shared libraries.
// Instrumentation
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
static void __attribute__((no_instrument_function))
log_func(const void* funcAddr, const char* action, const void* callSite)
{
char cmd[50];
snprintf(cmd, sizeof cmd, "addr2line -Cpfe /proc/%d/exe %p", getpid(), funcAddr);
fprintf(stderr, "%p %s %p ", callSite, action, funcAddr);
system(cmd);
}
extern "C" void __attribute__((no_instrument_function))
__cyg_profile_func_enter(void* this_fn, void* call_site)
{
log_func(this_fn, "->", call_site);
}
extern "C" void __attribute__((no_instrument_function))
__cyg_profile_func_exit(void* this_fn, void* call_site)
{
log_func(this_fn, "<-", call_site);
}
// Actual code we're tracing
#include <iostream>
struct Test
{
Test() { std::cout << "Hi, I'm Test constructor\n"; }
void method() const { std::cout << "And I'm Test method\n"; }
};
int main()
{
std::cout << "Hello, my name is main\n";
Test test;
test.method();
}
Compilation and running:
$ g++ test.cpp -o test -g -finstrument-functions && time ./test
0x8048b0b -> 0x804899b _GLOBAL__sub_I___cyg_profile_func_enter at /tmp/test.cpp:41
0x80489c4 -> 0x804890b __static_initialization_and_destruction_0(int, int) at /tmp/test.cpp:41
0x80489c4 <- 0x804890b __static_initialization_and_destruction_0(int, int) at /tmp/test.cpp:41
0x8048b0b <- 0x804899b _GLOBAL__sub_I___cyg_profile_func_enter at /tmp/test.cpp:41
0xf7a0de71 -> 0x804886a main at /tmp/test.cpp:37
Hello, my name is main
0x80488b1 -> 0x80489de Test::Test() at /tmp/test.cpp:32
Hi, I'm Test constructor
0x80488b1 <- 0x80489de Test::Test() at /tmp/test.cpp:32
0x80488c0 -> 0x8048a4a Test::method() const at /tmp/test.cpp:33
And I'm Test method
0x80488c0 <- 0x8048a4a Test::method() const at /tmp/test.cpp:33
0xf7a0de71 <- 0x804886a main at /tmp/test.cpp:37
real 0m0.062s
user 0m0.054s
sys 0m0.008s
There is a __FUNCTION__ (Reference) macro used to determine what method (in the format Class::Method) you're in, but this is more of a manual process.
However, when I needed the same 'trace' information recently, I could not find a automatic method.