[英]Dealing with similar code in multiple C “projects”
I am playing around with some C code, writing a small webserver. 我正在玩一些C代码,编写了一个小型Web服务器。 The purpose of what I am doing is to write the server using different networking techniques so that I can learn more about them (multithread vs multiprocess vs select vs poll). 我正在做的目的是使用不同的网络技术编写服务器,以便我可以更多地了解它们(多线程,多进程,选择,轮询)。 Much of the code stays the same, but I would like the networking code to be able to be "swapped out" to do some performance testing against the different techniques. 许多代码保持不变,但我希望可以将网络代码“交换出去”,以便针对不同的技术进行一些性能测试。 I thought about using ifdefs but that seems like it will quickly ugly up the code. 我考虑过使用ifdefs,但是看起来它将很快使代码变得丑陋。 Any suggestions? 有什么建议么?
Dynamic library loading? 动态加载库? eg dlopen
in Linux. 例如Linux中的dlopen
。
Just craft an API common to the component that requires dynamic loading. 只需为需要动态加载的组件设计通用的API。
I prefer pushing "conditional compilation" from C/C++ source to makefiles, ie having same symbols produced from multiple .c/.cpp files but only link in the objects selected by the build option. 我更喜欢将C / C ++源代码中的“条件编译”推入makefile,即具有从多个.c / .cpp文件生成的相同符号,但仅链接由build选项选择的对象。
Also take a look at nginx if you haven't already - might give you some ideas about web server implementation. 如果还没有的话,还可以看看nginx-可能会给您一些有关Web服务器实现的想法。
Compile the networking part into its own lib with a flexible interface. 通过灵活的接口将网络部分编译成自己的lib。 Compile that lib as needed into the various wrappers. 根据需要将该lib编译到各种包装中。 You may even be able to find a preexisting lib that meets your requirements. 您甚至可以找到满足您要求的预先存在的库。
Put the different implementations of the networking related functions into different .c files sharing a common header and than link with the one you want to use. 将与网络相关的功能的不同实现放入共享公共标头的不同.c文件中,然后与要使用的标头链接。 Starting from this you can make your makefile create x different executables this way for each of the different implementations you have done, so you can just say "make httpd_select" or "make httpd_poll" etc. 从此开始,您可以使makefile通过这种方式为完成的每个不同实现创建x个不同的可执行文件,因此您可以说“ make httpd_select”或“ make httpd_poll”等。
Especially for benchmarking to find the best approach it will probably give you more reliable results to do it at the compiler/linker level than via shared libraries or function pointers as that might introduce extra overhead at runtime. 尤其是对于进行基准测试以找到最佳方法而言,与通过共享库或函数指针进行编译相比,在编译器/链接器级别执行此操作可能会给您更可靠的结果,因为这可能会在运行时引入额外的开销。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.