I want to create an API which, on the call of a function, such as getCPUusage(), redirects to a getCPUusage() function for Windows or Linux. So I'm using a glue file api.h :

getCPUusage() {
    #ifdef WIN32
        getCPUusage_windows();
    #endif
    #ifdef __gnu_linux__
       getCPUusage_linux();
    #endif
} 

So I wonder if using inline would be a better solution, since with what I have, the call will be bigger.

My question is the following : is it better to use inlined function for every call in this situation ?

有帮助吗?

解决方案

It depends on use-case of your program. If consumer is still c++ - then inline has a sense. But just assume that you would like to reuse it inside C, Pascal, Java ... in this case inline is not a case. Caller must export someway stable name over lib, but not from header file. Lib for linux is rather transparent, while on Windows you need apply __dllexport keyword - that is not applicable to inline

其他提示

The answer is: yes, it is indeed more efficient, but probably not worthwhile:

If you're putting these functions in a class, it is not required that you write down the "inline" keyword in your situation, because you only have a header file (You don't have any cpp-files - according to your description). Functions that are implemented inside the class definition (in the header file) will be automatically seen as inline functions by the compiler. Note however that this is only a "hint" to the compiler. The compiler may still decide to make your function non-inline if that is found to be (by the compiler) more efficient. For small functions like yours, it will most likely produce actual inline functions.

If you're not putting these functions in a class, I don't think you should bother adding inline either, as (as said above) it's only a "hint" and even without those "hints", modern compilers will figure out what functions to inline anyway. Humans are much more likely to be wrong about these things then the compiler anyway.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top