0

Someone was recently reviewing a bit of code I am working on and told me that I should move some function declarations to the header file and call them static. Is the the preferred way of formatting c code and header files?

Per their suggestions my code now roughly looks like this:

header.h

# define USED_ONLY_IN_FILE1
# define USED_IN_BOTH

extern uint8_t var_used_in_both_files;
extern volatile uint8_t buffer_in_both_files[16];

static void funct_used_only_in_file1(void); //This used to live in file1.c without the static keyword
void funct_used_in_both_files(void);   

file1.c

#include "header.h"

uint8_t var_used_in_both_files;
volatile uint8_t buffer_in_both_files[16];

void funct_used_only_in_file1(void)
{
    var_used_in_both_files++;
}

void funct_used_in_both_files(void)
{
    buffer_in_both_files[0] = 1;
}

file2.c

#include "header.h"

void funct_b (void)
{
    var_used_in_both_files+=2;
    funct_used_in_both_files();
}

It feels a little weird to me that I now have a function essentially being declared static in both .c files when header.h is included. I'm still wrapping my head around keywords like static, extern, and volatile so I'd really appreciate an explanation of why we would want a function that's used only in one file to be declared in a header file then marked static. Why would we want this?

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
Indigo
  • 962
  • 1
  • 8
  • 23
  • 1
    There is a practice of having `static inline` functions in headers, not `static`. Other than that having anything but declarations in the headers is usually not a good idea. – Eugene Sh. Sep 05 '19 at 20:41
  • 3
    You should show the reviewer this question, and ask them if that's what they intended. I don't think it is what they intended. – user3386109 Sep 05 '19 at 20:44
  • @EugeneSh. Deos that mean I should basically take out everything from my header.h except the `void funct_used_in_both_files(void);` ? @uneven_mark in header.h I have `static void funct_used_only_in_file1(void);` which I used to have declared at the top of file1.c as just `void funct_used_only_in_file1(void);` – Indigo Sep 05 '19 at 20:51
  • @Indigo No, your header is containing only declarations. – Eugene Sh. Sep 05 '19 at 20:53
  • @Indigo I misread your question! – walnut Sep 05 '19 at 21:00

0 Answers0