Post

C++ Inline Compile

This post was migrated from Tistory. You can find the original here.

In a class definition, a function’s definition only needs to be linked together into a single executable by the linker after compilation.

1
2
3
4
5
6
7
8
9
10
11
12
13
//Car.h
#ifndef __Car_h__
#define __Car_h__

class Car {
private:
	int fuelGauge;
public:
	void getFuelGauge();
	void setFuelGauge(int fuel);
};

#endif
1
2
3
4
5
6
7
8
9
10
11
//Car.cpp
#include "Car.h"
#include <iostream>

inline void Car::getFuelGauge() {
	printf("now fuel : %d", this->fuelGauge);
}

inline void Car::setFuelGauge(int fuel) {
	this->fuelGauge = fuel;
}
1
2
3
4
5
6
7
8
9
//Main.cpp
#include "Car.h"

void main() {
	Car c;
	c.setFuelGauge(300);
	c.getFuelGauge();
	return;
}

If you apply inline to the functions in Car.cpp as shown above, compilation fails.

An inline function is one whose body gets inserted directly at the call site during compilation.

In other words, if get/set weren’t inline functions, Main.cpp would only need to confirm they’re member functions of the Car class, and compilation would succeed.

But because they’re inline functions, the calls to get/set need to be replaced with the function bodies themselves.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//Car.h
#ifndef __Car_h__
#define __Car_h__

class Car {
private:
	int fuelGauge;
public:
	void getFuelGauge();
	void setFuelGauge(int fuel);
};

inline void Car::getFuelGauge() {
	printf("now fuel : %d", this->fuelGauge);
}

inline void Car::setFuelGauge(int fuel) {
	this->fuelGauge = fuel;
}

#endif

So, as shown above, the function bodies need to live in the same file as the class declaration, so the compiler can reference them.

( The compiler compiles on a per-file basis — while compiling Main.cpp, it does not look at Car.cpp. )

This post is licensed under CC BY-NC 4.0 by the author.