问题
In my project I have an doSomething.m and soSomething.h files with the only C function:
void doSomething() {
}
The first question: what should I do to make this function accessible from any place in my code without needing to import any headers?
Note: I guess that to solve this problem the doSomething.h file is not needed at all, but its presence/absence is not a restriction.
I have the following pieces of knowledge but I can't have the whole picture of what is needed:
- I can use some another function with attribute((constructor)) that will be run at compilation runtime and it could do some manipulations to register doSomething;
- _class_addMethod_ adds methods on "runtime". But I don't know how to resolve "the class of global namespace";
- NSObject's + load method but it is not relevant here.
The second tricky question on top of the first: when I will have an answer to the first question, how can I then prevent "Implicit declaration of function 'doSomething' is invalid in C99" exactly for the function doSomething and not for the all others?
UPDATE: I forgot to exclude from the consideration the following options:
- .pch file, global headers
- The files where I want to use doSomething method should not contain any additional declarations like extern void doSomething()
回答1:
Well you cant really make it so you dont have to import a header, what you can do however is add the include into your pre compile header
Look in the "Supporting Files" folder in your project.
you will see a file like thise
<ProjectName>-prefix.pch
add your import at the bottom of this file. and every file will then have all the imports added here.
Note
I use Xcode
I guess if your using another IDE such as for GnuStep you would likely have another place similar. I dont know how the other IDE's work.
回答2:
In the file where you want to use it, import it:
extern void doSomething (void);
来源:https://stackoverflow.com/questions/14062042/how-to-dynamically-auto-register-c-function-so-it-could-be-available-through-the