I have a problem where i am linking multiple files in C. I want to define a constant representing array length at compile time, but save the user having to implement this in their file every time.
Here's the gist:
data.h - defines some constants
extern const int data[];
extern const int DATA_SIZE;
//other functions, not relevant
int get_second_item(void);
library_data.c - implements some of the functions in data.h
#include "data.h"
const int DATA_SIZE = sizeof(data) / sizeof(data[0]);
//can't compile because data is an incomplete type and hasn't been defined yet
int get_second_item(void)
{
return data[1];
}
public_data.c - user changes this with their data.
#include "data.h"
const int data[] = {1, 2, 3};
library_data.c and data.h are compiled first as .o files, amongst other library files that #include data.h and need to therefore use DATA_SIZE. Moving
const int DATA_SIZE = sizeof(data) / sizeof(data[0])
to public_data.c will of course work, but isn't a neat solution.