From my understanding inline functions can go in headers as well as in the source files (with inline keyword) and by default memeber functions defined in headers are tried be inline by the compiler.
My question is with following source files, add.h
#ifndef ADD_H
#define ADD_H
class Add {
public:
int add(int a, int b);
};
#endif /* ADD_H */
add.cpp
#include <iostream>
#include "add.h"
inline int Add::add(int a, int b) {
std::cout << "FUNC: " << __func__ << std::endl;
return a + b;
}
main.cpp
#include "add.h"
int main() {
Add a;
a.add(6,7);
return 0;
}
If i compile the add.cpp and main.cpp
g++ -c add.cpp
g++ -c main.cpp
g++ main.o add.o
It complains about
main.o: In function `main':
main.cpp:(.text+0x1a): undefined reference to `Add::add(int, int)'
collect2: error: ld returned 1 exit status
looking at the symbols in add.o,
U __cxa_atexit
U __dso_handle
000000000000003d t _GLOBAL__sub_I_add.cpp
0000000000000000 t __static_initialization_and_destruction_0(int, int)
U std::ios_base::Init::Init()
U std::ios_base::Init::~Init()
0000000000000000 r std::piecewise_construct
0000000000000000 b std::__ioinit
It doesn't have add function in it which i assume is because the function is inline in .cpp. My question is when we have shared libraries, is it required to define functions inline in headers (add.h in the example) so that source files (main.cpp in the example) using the library gets the functions inlined at obj creation itself? It made no difference when using -flto at linking because function isn't present in the add.o?