Inline Functions in C++
================
non-inline functions
================
For non-inline functions, if the prototype does not change, often the files that use the function need not be recompiled.
lib.cpp
main.cpp
$ g++ -c -fPIC lib.cpp
$ g++ -fPIC -shared -Wl,-soname,libref.so -o libref.so lib.o
$ g++ -c main.cpp
$ g++ -o main main.o -lref -L.
$./main
show 100 using style 1
Change
printf("show %d using style 1", i); to
printf("show %d using style 2", i);
$ g++ -c -fPIC lib.cpp
$ g++ -fPIC -shared -Wl,-soname,libref.so -o libref.so lib.o
$ ./main
show 100 using style 2
================
inline functions
================
lib.h
caller1.cpp
caller2.cpp
main.cpp
$ g++ -c *.cpp
$ g++ -o main *.o
$ ./main
show 100 using style 1
show 100 using style 1
Now change
printf("show %d using style 1", i); to
printf("show %d using style 2", i);
For the following commands:
$ g++ -c caller1.cpp
$ g++ -o main *.o
$ ./main
The result is
show 100 using style 2
show 100 using style 2
For the following commands:
$ g++ -c caller2.cpp
$ g++ -o main *.o
$ ./main
The result is
show 100 using style 1
show 100 using style 1
non-inline functions
================
For non-inline functions, if the prototype does not change, often the files that use the function need not be recompiled.
lib.cpp
#include <stdio.h>
void show(int i) {
printf("show %d using style 1
", i);
}
main.cpp
void show(int i);
int main(int argc, const char *argv[]) {
show(100);
return 0;
}
$ g++ -c -fPIC lib.cpp
$ g++ -fPIC -shared -Wl,-soname,libref.so -o libref.so lib.o
$ g++ -c main.cpp
$ g++ -o main main.o -lref -L.
$./main
show 100 using style 1
Change
printf("show %d using style 1", i); to
printf("show %d using style 2", i);
$ g++ -c -fPIC lib.cpp
$ g++ -fPIC -shared -Wl,-soname,libref.so -o libref.so lib.o
$ ./main
show 100 using style 2
================
inline functions
================
lib.h
#include <stdio.h>
inline void show(int i) {
printf("show %d using style 1
", i);
}
caller1.cpp
#include "lib.h"
void call1() {
show(100);
}
caller2.cpp
#include "lib.h"
void call2() {
show(100);
}
main.cpp
xtern void call1();
extern void call2();
int main() {
call2();
call1();
}
$ g++ -c *.cpp
$ g++ -o main *.o
$ ./main
show 100 using style 1
show 100 using style 1
Now change
printf("show %d using style 1", i); to
printf("show %d using style 2", i);
For the following commands:
$ g++ -c caller1.cpp
$ g++ -o main *.o
$ ./main
The result is
show 100 using style 2
show 100 using style 2
For the following commands:
$ g++ -c caller2.cpp
$ g++ -o main *.o
$ ./main
The result is
show 100 using style 1
show 100 using style 1