0

Context:

I'm writing a module in C which defines some very short functions. My gut instinct would be to declare them static inline in the .h file, but...

The question:

I understand that GCC at -O2 and above can choose to inline functions, whether or not they're defined static and/or inline. Given that, under what circumstances would you explicitly declare a function static inline in the .h file?

[FWIW, I'm inclined to trust the compiler...]

To make it concrete (omitting #includes and guards, etc):

Version A: with inline declarations

// File: bvec.h

static inline void bvec_set(size_t bit_index, uint8_t *store) {
  store[bit_index >> 3] |= (1 << bit_index & 0x7);
}

static inline void bvec_clear(size_t bit_index, uint8_t *store) {
  store[bit_index >> 3] &= ~(1 << bit_index & 0x7);
}

// File: bvec.c
// (empty)

Version B: trust the compiler's -finline-functions

// File: bvec.h

void bvec_set(size_t bit_index, uint8_t *store);

void bvec_clear(size_t bit_index, uint8_t *store);

// File: bvec.c

void bvec_set(size_t bit_index, uint8_t *store) {
  store[bit_index >> 3] |= (1 << bit_index & 0x7);
}

void bvec_clear(size_t bit_index, uint8_t *store) {
  store[bit_index >> 3] &= ~(1 << bit_index & 0x7);
}
E_net4
  • 27,810
  • 13
  • 101
  • 139
fearless_fool
  • 33,645
  • 23
  • 135
  • 217
  • 1
    There's a fundamental difference in your two approaches: the former *implicitly* gives access to the body code to any user of the header; the latter *can* hide that code in an object file or library. – Adrian Mole Jun 05 '21 at 18:33
  • @AdrianMole Good point: that's another reason to trust the compiler to do the optimization. – fearless_fool Jun 05 '21 at 18:58
  • Why `static`? `inline` is enough. – bolov Jun 05 '21 at 23:01
  • `-finline-functions` is enabled by default at most optimisation levels. As for the `inline` keyword, [does this answer your question](https://stackoverflow.com/questions/31108159/what-is-the-use-of-the-inline-keyword-in-c)? – n. m. could be an AI Jun 06 '21 at 09:38
  • @bolov Using both static with inline is better for optimizing code with most compilers. One reason is the the compiler can now it is not useful to generate any code for the function symbol. As a result the compiler can more aggressively inline functions in many tricky cases. One should keep in mind that compilers will not always remove the inlined functions calls (and replace them with the body of the functions). It is just an hint. – Jérôme Richard Jun 06 '21 at 20:01
  • As you say: Never optimize prematurely! If you don't have requirements on size or speed that can only be met with inlining, don't try to force it. -- In about 40 years of C programming in all fields (primitive 8-bit embedded to modern PCs) I remember just _one_ case where I needed inlining for a local function. Fortunately I could use GCC's capabilities to do this. -- However, this questions asks for opinions and might be closed... – the busybee Jun 07 '21 at 06:30

0 Answers0