FranXh
FranXh

Reputation: 4771

Converting C to C++: typdef generating error

I need to convert a .c file into .cpp file and I came across this declaration:

 typedef void handler_t(int);

 handler_t *Signal(int signum, handler_t *handler);

I included those two lines of code in the header file, and I add the actual function declaration function in the .cpp file.

 handler_t *Signal(int signum, handler_t *handler){ ...... } 

When I do this I get the error: "handler_t does not name a type".I have never worked before with typdef in C or C++, so can someone explain to me why I am getting an error?


My classes as requested:

 #ifndef A_H
 #define A_H

 class A
 {
     public:
       A();
       virtual ~A();

       typedef void handler_t(int);
       handler_t* Signal(int signum, handler_t *handler);

     protected:
     private:
 };

   #endif // A_H

/////////////

   #include "A.h"

   A::A()
   {
   }

   A::~A()
   {
   }

   handler_t* A::Signal(int signum, handler_t *handler) {

     ...........

    }

error:

    |694|error: ‘handler_t’ does not name a type|

Upvotes: 3

Views: 238

Answers (2)

Pete Becker
Pete Becker

Reputation: 76428

handler_t* A::Signal(int signum, handler_t *handler) {

The problem is that the first mention of handler_t needs to be qualified with A::. Like this:

A::handler_t* A::Signal(int signum, handler_t *handler) {

This is always the case when types defined inside a class are used as the return types of member functions. When you declare the function you're inside the class definition, so the nested typedef is known. And it's the same if you define the function inside the class definition. But once you step outside the class definition you have to tell the compiler where handler_t is defined. But the second mention of handler_t is okay, because at that point the compiler knows that it's compiling a member function of A, and it knows about the nested types in A.

Upvotes: 0

Jorge Israel Peña
Jorge Israel Peña

Reputation: 38616

Try changing it to:

typedef void (*handler_t)(int);

and:

handler_t Signal(int signum, handler_t handler);

For reference check out signal() which does it like this:

#include <signal.h>

typedef void (*sighandler_t)(int);

sighandler_t signal(int signum, sighandler_t handler);

Actually, looking at your new code, I think you have to do this:

A::handler_t* A::Signal(int signum, A::handler_t *handler)

I think your new error "undefined reference to main" is unrelated to the question asked. See this post for some ideas.

Upvotes: 2

Related Questions