Search code examples
c++linuxstrerror

Expected initializer before 'strerror'


I am trying to make a function like this which will print out the error details associated with it's error number, but i am getting the error error: expected initializer before 'strerror'. Here is the code

#include <iostream>
#include <cstring>

static char* messages[] = {
    "No error",
    "EPERM (Operation not permitted)",
    "ENOENT (No such file or directory)",
    "ESRCH (No such process)",
};
static const int NUM_MESSAGES = sizeof(messages)/sizeof(messages[0]);

extern "C" char * __cdecl strerror(int errnum)
{
  if (errnum < NUM_MESSAGES)
     return messages[errnum];
  return "Unknown error";
}

int main()
{
   int a;
   for(a=0;a<5;a++)
   {
       std::cout<<a<<" "<<strerror(a)<<"\n";
   }
   return 0;
}

How to solve this problem ? Thanks


Solution

  • I just realized that the answer I gave doesn't address the actual question. The key problem here is that when you #include <cstring> you get all the identifiers from the standard C header <string.h>, declared in namespace std. In addition, you might (and probably will) get all those names in the global namespace as well. So when you write your own function named strerror you'll get a direct conflict with the C function strerror, even if you sort out the __cdecl stuff correctly. So to write your own error reporting function, give it a name that's different from any name in the C standard library, and don't bother with extern "C" and __cdecl. Those are specialized tools that you don't need yet.

    char* error_msg(int erratum) {
        if (errnum < NUM_MESSAGES)
            return messages[errnum];
      return "Unknown error";
    }