Should C declarations match definition including keywords and qualifiers such as “static”, “inline”, etc

跟風遠走 提交于 2020-11-25 02:40:51

问题


Consider this example of a function declaration and definition (in the same translation unit):

inline static int foo(int x);

...

int foo(int x)
{
  return x+1;
}

I know that the types need to match, but what about other keywords and qualifiers? Should inline static be in both cases? Or just the declaration?

And which part of the C standard or which coding guideline could I use to justify the answer?


回答1:


No, for inline in particular, these should not be the same.

But the example is wrong from the start. For inline you need a definition (the whole function) with the inline in the .h file. By that, the inline, you avoid that the symbol is defined in several translation unit (.c) where you include the .h header.

Then, in exactly one translation unit you pout just the declaration without inline to indicate that the symbol should be generated in the corresponding .o object file.




回答2:


I want to provide detailed information about inline,

you can separate the declaration and definition fine, but that definition must be available in every translation unit that uses the function, i.e in your case inline static int foo(int x);

Inline functions are included in the ISO C99 standard, but there are currently substantial differences between what GCC implements and what the ISO C99 standard requires.

To declare a function inline, use the inline keyword in its declaration, like this:

static inline int
inc (int *a)
{
  return (*a)++;
}

An Inline Function is As Fast As a Macro

Note that certain usages in a function definition can make it unsuitable for inline substitution.

Note that in C, unlike C++, the inline keyword does not affect the linkage of the function.




回答3:


Yes. inline and static should be include. For example, the line of code for the function should be the same in the .h file where you declare, and the .c file where you define (so yes in both cases), but in your main code.c file it should only have the function name when called, so "foo(parameters passed)".

Hope this helps!




回答4:


You only need inline static in the declaration. You can leave it out of the function definition.

7.1.1/6:

A name declared in a namespace scope without a storage-class-specifier has external linkage unless it has internal linkage because of a previous declaration and provided it is not declared const. Objects declared const and not explicitly declared extern have internal linkage.



来源:https://stackoverflow.com/questions/42962906/should-c-declarations-match-definition-including-keywords-and-qualifiers-such-as

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!