When to put static function definitions in header files in C?

前端 未结 6 679
别跟我提以往
别跟我提以往 2020-12-01 05:53

I\'ve come across some code that has a large static function in a header file and i\'m just curious when it is/is not ok to do this. For example, if many .c fil

6条回答
  •  南笙
    南笙 (楼主)
    2020-12-01 06:17

    Can also be useful to define functions with static work buffers to be local to each translation unit. A particular example is strtok(). strtok() marches through a buffer one token per call. If strtok() calls are interleaved from two different places (i.e. two different translation units) then the results are not what is expected/desired. If each translation unit had its own copy of strtok() and therefore each translation unit had its own strtok() static variables, then this kind of stomping on the internal state would go away. If state stomping is happening, then both (sets of) calls are in the same translation unit and the debugging has some semblance of locality.

    (Note that the "correct" solution is to replace strtok() with a stateless function and make the callers responsible for holding context and state information, the same way fopen() and friends make the caller hold a FILE for each context.)

提交回复
热议问题