2

I used code blocks to make a project with main.c:

#include <stdio.h>
#include "t.h"

int main()
{
    printf("%c\n", return_f('f'));
    printf("%c\n", return_f(return_char(71)));
    printf("%d\n", STATIC_INT);

    return 0;
}

And t.h:

static int STATIC_INT = 14;

static unsigned char return_char(char n){
    return (n/2 + 9);
}

unsigned char return_f(char n){
    return ((n=='f' || n=='F') ? n+1 : 'f');
}

Since I assume static should limit globals and functions to their files, how does it allow to run/print out:

g
f
14

Or is that just not how it's supposed to work?

EpichinoM2
  • 137
  • 2
  • 10
  • 2
    Possible duplicate of [Static functions declared in "C" header files](https://stackoverflow.com/questions/42056160/static-functions-declared-in-c-header-files) –  Oct 05 '18 at 11:43
  • If in Linux and using gcc; try this gcc -E main.c you should be able to figure out the rest – asio_guy Oct 05 '18 at 12:17
  • @JETM Not a duplicate IMO. The question you linked is about just declaring in the .h but still defining in the .c. This question is about defining in the .h. – Joseph Sible-Reinstate Monica Oct 06 '18 at 03:25

3 Answers3

3

t.h is included textually before the actual compilation process takes place. Therefore static int STATIC_INT = 14; is part of your main.c file.

The real problem is that you are declaring variables in a header file which is almost always wrong.

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
2

It work because you import t.h in your .c file.

Static function can't be accesible outside of the file. But when you import t.h in your main.c file, all the code in t.h will be paste into main.c; so now your static function belong to main.c !

Loufi
  • 1,215
  • 1
  • 8
  • 23
0

You have included t.h in your main.c, so these symbols are in the same unit of your main.c

Stargateur
  • 24,473
  • 8
  • 65
  • 91