Static functions in C

2019-05-13 18:37发布

I have a software module that consists of a *.h file and a *.c file. Variable and function declarations are located in the *.h file, whilst function definitions are located in the *.c file. Two functions within the module are helper functions that are not intended to be used outside of the module.

What is the best method of making this intent clear to users of the module?

I tried declaring the functions static, but doing so in the *.h file results in the GCC compiler warning that the functions are "declared static but never defined". How is it that the *.h and *.c files are treated as different translation units, even though the *.c file uses the #include directive to include the *.h file?

Is there a solution to this problem that does not involve placing the declarations of the functions that are to be made static in the *.c file, along with their definitions? Whilst this solution does work, it breaks what I thought was the good practice of keeping declarations in a header file and definitions in an implementation file.

3条回答
可以哭但决不认输i
2楼-- · 2019-05-13 18:42

How is it that the *.h and *.c files are treated as different translation units, even though the *.c file uses the #include directive to include the *.h file?

The header is typically also included in other source files. That's the reason for the warning.

If you compile other files including the header, you indeed have a function declared that is not defined.

The good practice is to declare static functions in the source file they are defined in, since that's the only file they are visible in.

查看更多
戒情不戒烟
3楼-- · 2019-05-13 19:01

static declarations should not appear in header files (except inline ones, I'll ignore that for now). If you want a function that appears only inside the module, don't put it in the .h file at all. The .h file is for external consumption. Put the static functions inside the .c file. Note that you can still forward declare the function if you need.

查看更多
放荡不羁爱自由
4楼-- · 2019-05-13 19:01

Declare static functions in the source file they are defined in (please also provide prototype), since that's the only file they are visible in.

Duplicate: function declared static but never defined

查看更多
登录 后发表回答