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 回答