1

次のようなクラスと実装を含む大量のヘッダーがあるとします。

// header.h
#ifndef MYHEADER
#define MYHEADER
class myClass {
public:
    int one()
    {
        return 1;
    }
    int two();
};
#endif // MYHEADER

およびいくつかの関数実装を含むいくつかの cpp ファイル:

// header_impl.cpp
#include "header.h"
int myClass::two()
{
    return 2;
}

.lib(.a)ライブラリバンドルに実装するint one()か、ヘッダーにとどまってコンパイルするのは、libを使用する人がいる場合にのみコンパイルするため、このヘッダーはそこのコードで使用する傾向があります(そして、彼のコードにコンパイルされますが、新しい.lib (.a) ファイルに表示されます)?

ヘッダー ファイル内で定義された関数の実装は、スタティック ライブラリにコンパイルされますか?

4

2 に答える 2

1

Assuming the function is not used by any of the library functions itself, and no library function takes its address [makes a function pointer], then the compiler has no reason to make a "real function" of it. Of course, since inlining is really a question of "compiler decides", it's entirely possible that the compiler decides to NOT use the function inline, and in fact make one in the object file where it is compiled.

But in general, for small functions, no, it will only exist as source code in the header, and then get inlined wherever it is called.

于 2013-02-07T19:52:33.587 に答える
1

Maybe, in that a cpp almost definitely includes that header within your static library. Generally just because it's defined in the class doesn't force it to be inline, but it does definitely specify that the function has an ODR exception (which I think I called inline linkage; More on that later). So, depending on the function and it's use from within the static library it may or may not have an actual definition, depending on if the compiler inlined it and if it's being used at all.

If the compiler decided not to inline your function, when you #include that header from a exe which links with the static library you might think it should then get defined again, and break the one definition rule. But, you'd be wrong. Because the fact that the method is defined within the class body marks the function as having an ODR expection. Ultimately it's up to the compiler which definition it will choose (the one in the static library or the one in the exe/whatever). Likely it will choose the first one it sees.

Note: You can achieve the ODR exception by defining the function outside of the class body and using the inline keyword.

于 2013-02-07T19:52:40.020 に答える