18

I cannot understand what the errno library in c++ is for? What types of errors are set in it and how do I know which number stands for which error?

Does it affect program execution?

David
  • 14,047
  • 24
  • 80
  • 101
Cool_Coder
  • 4,888
  • 16
  • 57
  • 99
  • Take any man-page and look at the 'Errors' section, eg. http://linux.die.net/man/3/open. All `E*` macros are values `errno` will contain upon error. – wormsparty Oct 26 '11 at 10:05
  • 1
    Related, see [Is errno thread-safe?](https://stackoverflow.com/q/1694164/608639) It provides several good references for `errno`. – jww Jun 05 '18 at 08:25

1 Answers1

19

errno.h is part of the C subset of C++. It is used by the C library and contains error codes. If a call to a function fails, the variable "errno" is set correspondingly to the error.

It will be of no use if you're using the C++ standard library.

In C you have functions that translate errno codes to C-strings. If your code is single threaded, you can use strerror, otherwise use strerror_r (see http://www.club.cc.cmu.edu/~cmccabe/blog_strerror.html)

For instance in C it works like this:

 int result = call_To_C_Library_Function_That_Fails();

 if( result != 0 )
 {
    char buffer[ 256 ];
    strerror_r( errno, buffer, 256 ); // get string message from errno, XSI-compliant version
    printf("Error %s", buffer);
     // or
    char * errorMsg = strerror_r( errno, buffer, 256 ); // GNU-specific version, Linux default
    printf("Error %s", errorMsg); //return value has to be used since buffer might not be modified
    // ...
 }

You may need it of course in C++ when you're using the C library or your OS library that is in C. For instance, if you're using the sys/socket.h API in Unix systems.

With C++, if you're making a wrapper around a C API call, you can use your own C++ exceptions that will use errno.h to get the corresponding message from your C API call error codes.

user766308
  • 103
  • 7
Nikko
  • 4,182
  • 1
  • 26
  • 44
  • does this work on windows...because i found on web that it works only on unix – Cool_Coder Oct 26 '11 at 10:17
  • 1
    Almost correct, but many functions just return s single value (such as `-1`) on failure, and set `errno` to the actual error code. So you'd want `strerror_r(errno,...)` rather than `strerror_r(errorCode,...)`. `errno` itself is a freaky pseudo-global variable. – Mike Seymour Oct 26 '11 at 10:59
  • @MikeSeymour oh yes you're right. Last time I checked, errno was a thread-local variable on my linux so it is kind of safe. It is/was not always the case I guess. – Nikko Oct 26 '11 at 11:11