在静态声明中包含 header 会发生什么?

What happens when including header with static declarations?

例如,假设我有 2 个 header 文件。

a.h

#include <stdio.h>
static __inline foo()
{
    // do something
}

然后 a.h 文件被包含到 b.h:

b.h

#include "a.h"
void bar();

与对应的b.cpp文件:

b.c

#include "b.h"
void bar()
{
 foo();
}

main.c

#include "b.h"
void main()
{
 bar();
}
  1. foo() 是否会内联到 b.c 文件中?
  2. foo()(静态)是否会在 main.c 文件中可见,因为它是通过 b.h 文件包含的,还是仅对 b.c 可见? (猜测它不会可见,因为它们不在同一个翻译单元中)。

foo()bmain 中都可见。编译器在预处理器完成工作后查看文件。

main.c 在预处理器步骤之后:

<all the stuff from stdio.h>
static __inline foo()
{
    // do something
}
void bar();
void main()
{
 bar();
}

main.c 中删除 foo() 的一种方法是将 a.hb.h 移至 b.c:

已修改 b.h

void bar();

已修改 b.c

#include "a.h"
#include "b.h"
void bar()
{
 foo();
}

Is foo() going to be inlined in b.c file?

不如把"inlined"说成函数bar()。可能是,但不能保证。是否内联函数是编译器的决定。将函数标记为内联通常只是一个提示,可能会被忽略。请参阅您的编译器文档以阐明实际行为。

Is foo() (static) going to be visible in main.c file since it's included via b.h file or it will be just visible to b.c? (Would guess that it won't be visible since they are not in same translation unit).

foo() 在每个直接或间接包含 a.h 的翻译单元中可见。假设省略了内联,还有另一个有趣的点:每个翻译单元都定义了自己的 foo() 副本,即 foo() 的机器代码将为每个编译源生成。这对 non-trivial 函数来说可能是一种浪费,因为它会导致生成的代码膨胀。因此,您应该在 headers 中定义静态函数,前提是它们很小并且打算内联。