Design Code in Multiple Files
terminal用时方恨...没好好学linux
Compilation Process
Starting with source code (e.g. C++) and converting it into machine code that the computer can run.


Separate Declaration from Definition
// functions.h
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
int gcd(int, int);
int factorial(int);
int mod_pow(int, int, int);
#endif
// functions.cpp
#include “functions.h”
int gcd(int a, int b) {…}
int factorial(int n) {…}
…
Group Related Functions Together
// math functions
#ifndef MATH_H
#define MATH_H
…
double exp(double);
double log(double);
double pow(double, double);
double sqrt(double);
…
#endif
// string functions
#ifndef STRING_H
#define STRING_H
…
int find(string, string);
int length(string);
string lower(string);
string upper(string);
string reverse(string);
…
#endif
Header Guards
#ifndef NAME_OF_FILE_H
#define NAME_OF_FILE_H
…
#endif
Prevents double inclusion: inclusion of same header file multiple times
Helps prevent linker error due to multiple definitions (re-definition)
#ifndef
pre-processor directive “if not defined"
Including and Compiling
// source1.cpp
#include <c++_library>
#include <c_library.h>
#include
“user_defined_library.h”
…
// source2.cpp
#include
<iostream>
…
int main() {…}
//$ g++ source1.cpp source2.cpp source3.cpp
Last updated
Was this helpful?