Let's say I'm in this sitation:
main.c :
#include <stdio.h> #include <stdlib.h> #include "header.h" int iCanProcess (char* gimmeSmthToProcess); int processingFunctionsCount = 0; int (*(*processingFunctions)) (char*) = NULL; int addProcessingFunction(int (*fct)(char*)) { processingFunctionsCount++; processingFunctions = realloc(processingFunctions, sizeof(int (*)(char*))*ProcessingFunctionsCount); processingFunctions[processingFunctionsCount-1] = fct; } int main(int argc, char *argv[]) { char* dataToProcess = "I am some veeeery lenghty data"; addProcessingFunction(iCanProcess); [ ... ] for(unsigned int i = 0; i < processingFunctionsCount; i++) { processingFunctions[i](dataToProcess); } free(processingFunctions); return 0; } int iCanProcess (char* gimmeSmthToProcess) { ... }
somefile.c :
#include "header.h" int aFunction(char* someDataToProcess) { ... }
header.h :
#ifndef HEADER_DEF #define HEADER_DEF extern int processingFunctionsCount; extern int (*(*processingFunctions)) (char*); int addProcessingFunction(int (*fct)(char*)); #endif
Is there ANY way, using macros or any other trick, I can add aFunction
to the array of pointer-to-functions processingFunctions
without changing main.c
or header.h
every time I need to add one ?
The problem here is not to change the array as it can be reallocated easily, but to NOT change main()
function: there must be a way I can be aware of the file being here and compiled, and fetch the function prototype while staying outside of main()
I thought about using a preprocessor trick like this one but don't seem to find a proper way to do it...
(Side-note : This is a trimmed-down version of a bigger project, which in fact is base code to support parsers with the same output but different input. Some parsers support some type of files, so i have an array of function pointers (one for each parser, to check if they are compatible) and I call each one of them against the file contents. Then, I ask the user to chose which parser it wants to use. I have one file per parser, containing a "check" function, to see if the parser can handle this file, and a "parse" function to actually do all the hard work. I can't change the header or the main.c files every time I add a parser. )
(Side-note 2 : this title is terrible... if you have any idea for a better one, please oh PLEASE feel free to edit it and remove this note. Thanks)