Evan
Evan

Reputation: 663

In C, should inline functions in headers be externed in the .c file?

I've seen a few questions addressing this general topic, but I'm still unsure exactly what the correct approach is for ISO C, and how that may or may not vary from GNU C.

If I have some function inline void foo() in file.h defined with the inline keyword, should I also declare that function in file.c as extern void foo();? Assume that multiple .c files will include file.h.

From what I've read the answer seems to be "yes" and have something to do with how the compiler looks for definitions emitted by other translation units, but to be honest I don't fully understand the implications.

I'm working on a project right now that has a lot of functions declared inline within the header files, and none of those functions are declared in the corresponding .c files. Everything compiles without gcc complaining, but is this approach actually correct?

Upvotes: 4

Views: 2528

Answers (2)

R.. GitHub STOP HELPING ICE
R.. GitHub STOP HELPING ICE

Reputation: 215567

Yes, if you use inline without static, there needs to be an actual external definition of the function somewhere in case the compiler declines to inline it in one or more places. The canonical way to do that is to make a source file containining (using your example names) nothing but:

#include "file.h"
extern void foo();

Personally, I find extern inline semantics in C confusing and messy, and prefer to avoid them entirely by making all inline functions static. Of course this wastes space with multiple instantiations of the function if the compiler declines to inline, but you should not be doing this with functions of nontrivial size anyway.

Upvotes: 8

Brecht Sanders
Brecht Sanders

Reputation: 7305

inline means the compiler will expand that function where it is used in the code (instead of calling it as a function). That means that an inline definition in a header file with the function implementation in a .c file makes no sense, as wherever you include the header in another .c file the function can't be expanded inline as its code implementation is not known.

So you should keep the inline function and its code implementation in the header file.

Upvotes: -1

Related Questions