1

I'm a little confused about the use of header-only files in cpp . From my understanding, I need to declare all functions and variables with "inline". For classes/structs, I don't need to apply inline because it's already declared implicit.

Example: In app.hpp file

namespace app{
    inline void func1(){#do sth};
    inline int num;
    class application{
        void func2();//this should be fine;
        void int num2;
    }
}

Why it's necessary to declare all variables and functions with inline? It works properly if I declare function in .hpp and define functions in .cpp files without inline, but I have to do header-only.If not using inline, it will shows multiple-definition error.(If I declare with static instead of inline, it shows not error at compile time but shows wrong outputs when I run it) Thanks for anybody's help!

Alanaa
  • 75
  • 8
  • 1
    See [here](https://en.cppreference.com/w/cpp/language/inline) for information about what `inline` actually means. See [this question](https://stackoverflow.com/questions/1759300/when-should-i-write-the-keyword-inline-for-a-function-method) for a much bigger discussion. – Nathan Pierson Nov 02 '22 at 16:46
  • 1
    I think you've misunderstood what `inline` means. See [c++ inline function?](https://stackoverflow.com/questions/5971736/c-inline-function) – Jason Nov 02 '22 at 16:46
  • 2
    inline promises the compiler and linker that all implementations of the function it finds will be the same. And this is important because your header file may be compiled many times. And thus your function will end up in many object files. inline allows the linker just to pick one, without inline it see multiple `instances` of your function. Thus inline has nothing to do with "expanding the code" to avoid a function call. – Pepijn Kramer Nov 02 '22 at 16:46
  • 2
    But summarizing those links: The `inline` specifier tells the compiler that it's okay for multiple definitions of a given thing to appear in multiple translation units because all those definitions will be identical. It's unnecessary for classes because they're already inline. The `static` specifier creates a definition with internal linkage, meaning that instead of each translation unit sharing a definition of `num`, there's a separate `num` for each source file. – Nathan Pierson Nov 02 '22 at 16:48

0 Answers0