I am looking for a (clean) way of writing a function definition and a function prototype without duplicating code. Since DRY has established itself as a good idea and manual prototyping in header files is a clear violation, this seems like a reasonable requirement.
The sample code below shows a (rough) way to solve a preprocessor problem. It seems unlikely to be optimal, but it seems to work correctly.
Using separate files and duplication:
foo.h:
#ifndef FOO_H
#define FOO_H
int dofoo(int a);
#endif
foo.c:
#include "foo.h"
int dofoo(int a) {
return a * 2;
}
Using C preprocessor:
foo.h:
#ifndef FOO_H
#define FOO_H
#ifdef PROTOTYPE
#error "PROTOTYPE set elsewhere, include mechanism will fall over"
#endif
#define PROTOTYPE
#include "foo.c"
#undef PROTOTYPE
#endif
foo.c:
#include "foo.h"
int dofoo (int a)
#ifdef PROTOTYPE
;
#else
{
return a * 2;
}
#endif
- .h .c! . , . , .
, .
- , .
- (, sqlite makeheaders)
, . C - 25 , , , .
, .
edit: gcc 4.8.2 clang 5.1
. #endif ( , ) "error: unterminated #else" "error: unterminated ", #ifdef.
#else , C. gcc "error: '(' before '{' " clang " ". , , #else .
PROTOTYPE wrong , , . , , , , , .