Home > Blockchain >  Typedef after incomplete type definition
Typedef after incomplete type definition

Time:11-12

I'm need to declare incomplete type (may it be siginfo_t) in header, and in source import some system header (sys/signal.h), that defines that type.

So, here is the problem:

// a.h
struct siginfo_t;
void foo(siginfo_t*);
// a.cpp
#include "a.h"
#include <signal.h> 
void foo(siginfo_t* x) { /* implementation */ };

But in signal.h it is defined like:

typedef struct siginfo_t { /* */ } siginfo_t;

Compiler error: error: typedef redefinition with different types ('struct siginfo_t' vs 'siginfo_t').

How to achieve no errors there? Thanks!

CodePudding user response:

In the header <sys/siginfo.h> the typedef name siginfo_t is an alias for an unnamed structure

typedef struct {
    int si_signo;
    int si_code;
    union sigval si_value;
    int si_errno;
    pid_t si_pid;
    uid_t si_uid;
    void *si_addr;
    int si_status;
    int si_band;
} siginfo_t;

But you introduced the same alias name for named structure

typedef struct siginfo_t { /* */ } siginfo_t;

So the compiler issues the error

error: typedef redefinition with different types ('struct siginfo_t' vs 'siginfo_t')

because you may not introduce the same alias name for a named structure and an unnamed structure. These structures are different types.

CodePudding user response:

So, there is the right approach:

// a.h
#pragma once
extern "C" {
    struct siginfo;
}
void foo(siginfo*);
// a.cpp
#include "a.h"
#include <sys/siginfo.h>
void foo(siginfo* x) { /* */ };
  • Related