How to dynamically auto-register C function so it could be available through the whole project without any imports/headers/externs/.pch-files?

点点圈 提交于 2019-12-13 05:42:43

问题


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:

  1. .pch file, global headers
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!