Search code examples
cheader-filesc89

Can I use extern function declaration on a C Header which is also used for the C source file which contains the function definition?


I have the following source code in C89:

routine_a.c:

struct DataRoutineA routineA(int a, int b) {
  struct DataRoutineA data = (struct DataRoutineA *) malloc(sizeof(DataRoutineA));
  data.a = a;
  data.b = b;
  return data;
}

and the following header file:

routine_a.h:

struct DataRoutineA {
  int a;
  int b;
};

extern struct DataRoutineA routineA(int a, int b);

The intention of routine_a.h is that it could be used as header for other source code files. Hence the struct is defined and also the extern function definition. In that case my understanding is that the header is properly defined.

However, what happens with the extern clause if this header is also used for routine_a.c? Which was the way to fix this in ANSI C/C89? Do I need two different headers for this case?


Solution

  • All functions in C are by default extern. So there is no difference between

    extern struct DataRoutineA routineA(int a, int b);
    

    and

    struct DataRoutineA routineA(int a, int b);
    

    You do need the extern keword when declaring function prototypes at all.