C : differences between prototype declaration in header and function declaration for implementation?

StackOverflow https://stackoverflow.com/questions/719189

  •  23-08-2019
  •  | 
  •  

Question

I was wondering about little differences between declaration of function prototypes in headers and in .c files. I have a header with some prototype functions and a some .c files with real implementation of these functions. I made some changes in the header, only added "__restrict" qualifier (recognized by gcc). My question is do I have to put the "__restrict" qualifier in .c files to (currently the code compile so I guess the answer is no, but some precision would be appreciated).

Does this work for every C qualifier? Can I add some "const" or "volatile" in header without having to do the same in .c files?

currently in header :

int myfunc_gettype (const mytype *__restrict, int *__restrict);

and in implementation file :

int myfunc_gettype(const mytype *attr, int *type)
Was it helpful?

Solution

You must. The mismatch invokes undefined behavior. Is there some reason why you want to have separate declarations in the header and at definition?

Note well, that the keyword is restrict as opposed to __restrict which is a vendor extension (hint: look at the _'s before the keyword name). You should stick to the standard version for portability.

OTHER TIPS

With gcc 4.0.1, it depends on whether the const is pointless:

// Who cares, compiles fine, but irks the maintenance programmer.

// f.h
int f(const int i);

// f.c
int f(int i) { return i += 42; }


// No no no no Your Types Conflict gcc will not stand for it

// f.h
int f(const int *pi);

// f.c
int f(int *pi) { return (*pi)+= 42; }

NOTE: You haven't actually added the 'restrict' qualifier. You just have different (optional) variable names in the prototype.

As to your question, most good C compilers will catch this bug and throw a warning/error if the non-matching prototype is #included with the implementation. If you have mismatching prototypes, you may see problems ranging from subtle to instant crash.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top