0

In C or C++ you can declare a function to be static if it is only used in a single Translation Unit (i.e. file), for example:

static int square(int a) {
    return a * a;
}

This should allow the compiler to optimise it better. It's a bit ugly though (edit: opinions on the ugliness may vary; this question isn't about that), and I'd rather not have to do it if I don't need to. How much difference does it really make?

  1. Does it affect compile times?
  2. What is the overhead for calling a non-static function that could be static?
  3. Can the linker recognise that it is only used in one file and automatically turn it back into a static function (maybe with -flto or ThinLTO?).

Edit: Answers for any achitecture & compiler are welcome, though obviously more common ones are more helpful (Clang, x86-64).

Timmmm
  • 88,195
  • 71
  • 364
  • 509
  • 1
    Please narrow down the specific compiler(s) you're asking this question for. It's very compiler-dependant. With LTO they'll definitely get optimized out. – tambre Oct 27 '17 at 13:48
  • 1
    "_It's a bit ugly though_" Why is it ugly? If the function is helper function inside a translation unit, and should not be callable externally, why should it have external linkage? – Algirdas Preidžius Oct 27 '17 at 13:48
  • 7
    A major reason to do this is to prevent name clashes with similar functions in other units, which will cause silent undefined behaviour. There's no reason not to do it really. – M.M Oct 27 '17 at 13:49
  • 4
    `static` is about as ugly as `private`. No matter your taste, hiding names is useful without even considering optimization. – nwp Oct 27 '17 at 13:50
  • 4
    I always do this religiously, duplicate symbol definitions in large projects are not much fun. Especially important when you use a name like that. C++ has namespace support so it is a lot less critical. – Hans Passant Oct 27 '17 at 13:50
  • 3
    It affects linking times more than compile times. – ratchet freak Oct 27 '17 at 13:52
  • 3
    Note - in C++ you better use anonymous namespace. – Slava Oct 27 '17 at 13:54
  • @Slava: They are effectively the same for functions. See [this answer](https://stackoverflow.com/a/4422554/265521). – Timmmm Oct 27 '17 at 13:56
  • 3
    @Timmmm They are not the same for everything else, that already good enough reason to use anonymous namespace for everything, rather than differentiate it. – Slava Oct 27 '17 at 13:59

0 Answers0