Sir DrinksCoffeeALot Sir DrinksCoffeeALot - 3 months ago 7
C Question

What happens when including header with static declarations?

For example, let's say I have 2 header files.

a.h

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


Then
a.h
file gets included into
b.h
:

b.h

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


With corresponding
b.cpp
file:

b.c

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


main.c

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



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

  2. 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).


Answer

foo() is visible in both b and main. The compiler sees the files after the preprocessor has done its job.

main.c after the preprocessor step:

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

One way to remove foo() from main.c is to move inclusion of a.h from b.h to b.c:

Modified b.h:

void bar();

Modified b.c:

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