Headers and source files: splitting a program
All your programs so far fit in a single file. A real project has dozens or hundreds, and putting everything in main.cpp would be unmanageable and would force recompiling everything after any change. C++ solves this with separate compilation: each .cpp file (translation unit) is compiled on its own into an object file, and then the linker joins them into the executable. For one .cpp to use what is defined in another, it needs to know its declarations, and that is the job of header files (.h or .hpp).
Declaration and definition
A declaration says that something exists and how it is used (the name, the types); a definition implements it. The one definition rule (ODR) requires each function, variable or class to have exactly one definition in the whole program, although it can have many declarations. That is why the header contains declarations: the class with the signatures of its methods, the function prototypes. The corresponding .cpp contains the definitions. The header is included with #include "name.h" (quotes for your files, angle brackets for the standard library). The preprocessor literally copies the header's contents where you include it.
// ---- account.h ----
#pragma once // include guard: this file is processed once per .cpp
#include <string>
class Account {
public:
Account(std::string owner, double balance);
void deposit(double amount);
bool withdraw(double amount);
double balance() const;
const std::string& owner() const;
private:
std::string owner_;
double balance_;
};// ---- account.cpp ----
#include "account.h"
#include <utility>
Account::Account(std::string owner, double balance)
: owner_{std::move(owner)}, balance_{balance} {}
void Account::deposit(double amount) {
if (amount > 0) {
balance_ += amount;
}
}
bool Account::withdraw(double amount) {
if (amount <= 0 || amount > balance_) {
return false;
}
balance_ -= amount;
return true;
}
double Account::balance() const { return balance_; }
const std::string& Account::owner() const { return owner_; }// ---- main.cpp ----
#include <iostream>
#include "account.h"
int main() {
Account acc{"Ana", 100.0};
acc.deposit(25.5);
bool ok = acc.withdraw(500.0);
std::cout << acc.owner() << ": " << acc.balance() << " (withdraw ok: " << ok << ")\n";
// Ana: 125.5 (withdraw ok: 0)
return 0;
}Guards, compilation and typical errors
If two headers include a third one, the compiler would see the same class defined twice in a .cpp and fail. The protection is the include guard: #pragma once on the first line (very widespread) or the classic pattern #ifndef NAME_H / #define NAME_H / #endif. To compile the two source files and link them with g++ you write: g++ -std=c++17 -Wall -Wextra main.cpp account.cpp -o app. With clang++ it is the same. Each .cpp is compiled separately, and if you change only account.cpp it would be enough to recompile that file and link again; build systems like CMake (the next lesson) automate that decision.
- "undefined reference to ...": you declared something but forgot to add the .cpp with its definition to the compile command.
- "multiple definition of ...": you defined a normal function in a header included from several .cpp files; move it to the .cpp or mark it inline.
- "redefinition of class ...": the include guard is missing.
- Templates: their full definition goes in the header, because the compiler needs it to instantiate them.
- Never put using namespace std; in a header: it pollutes everyone who includes it.
Good organization: one .h/.cpp pair per class (account.h, account.cpp), lowercase file names, and include only what is needed in each header. If in the header you only use a type through a pointer or reference, a forward declaration (class Customer;) is sometimes enough instead of including its full header, which speeds up compilation. In the .cpp, include your own header first: that way you check that it is self-sufficient and does not depend on includes you forgot to put in it.
✎ Мои заметки
Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов