C header causes errors when included in some files but not others
The title pretty much says it all. The precise error message that seems to be the root of it is:
util.h:4: error: expected declaration specifiers or ‘...’ before ‘size_t’
The header in question is:
#ifndef UTIL_H
#define UTIL_H
void print_array(void*, int, size_t, void (*)(void*));
extern void print_int(void*);
extern void print_float(void*);
#endif /* UTIL_H */
If I compile the following file with gcc -Wall -c util.c
the compiler silently creates an object file.
#include <stdio.h>
#include "util.h"
void print_array(void* a, int length, size_t size, void (*print)(void*)) {
unsigned int i;
for (i = 0; i < length; i++) {
print(a + i*(unsigned int)size);
}
printf("\n");
}
void p开发者_Go百科rint_int(void* i) {
int* a = (int*) i;
printf(" %i ", *a);
}
void print_float(void* f) {
float* a = (float*) f;
printf(" %f ", *a);
}
If I include it with any other file, I get the aforementioned error and a bunch of other ones. The one I've provided comes first. Everything I've googled about it says that it's the result of a syntax error on a previous line but it was happening when it was the first line in the file. I can see that if I get this error knocked out, then all the other ones will go away as they have to do with print_array
being called with the wrong number or type of arguments (which it isn't).
size_t
isn't defined until you include stddef.h
. Your header should probably include that first to guarantee it's defined. (As it stands, you're just getting "lucky" and having other includes that will eventually define it included first, so it doesn't cause a problem.)
精彩评论