헤더 파일에서 함수 프로토타입 사용하기
이 단계에서는 함수 프로토타입과 C++ 에서 헤더 파일을 사용하여 함수를 구성하고 선언하는 방법에 대해 배우게 됩니다. 함수 프로토타입은 함수의 구현 (함수의 본문) 을 제공하지 않고 함수의 이름, 반환 타입 및 매개변수를 선언합니다. 헤더 파일을 사용하면 함수의 인터페이스 (선언) 와 구현을 분리할 수 있습니다. 이러한 분리는 코드 구성을 개선하여 프로그램의 여러 부분이나 여러 프로그램에서 함수를 유지 관리하고 재사용하기 쉽게 만듭니다.
WebIDE 를 열고 ~/project 디렉토리에 세 개의 파일을 만듭니다.
먼저 math_functions.h를 만듭니다.
touch ~/project/math_functions.h
math_functions.h에 다음 코드를 추가합니다.
#ifndef MATH_FUNCTIONS_H
#define MATH_FUNCTIONS_H
// 수학 연산을 위한 함수 프로토타입
int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);
double divide(double a, double b);
#endif // MATH_FUNCTIONS_H
.h 파일은 함수 프로토타입 및 기타 선언을 포함하는 선언에 사용되며 구현은 포함하지 않습니다. 이런 식으로 구현 없이 함수를 선언할 수 있습니다. #ifndef, #define, #endif 지시문은 include guard 라고 하며, 헤더 파일의 중복 포함을 방지하여 오류를 일으킬 수 있습니다.
다음으로 math_functions.cpp를 만듭니다.
touch ~/project/math_functions.cpp
math_functions.cpp에 다음 코드를 추가합니다.
#include "math_functions.h"
// 함수 구현
int add(int a, int b) {
return a + b;
}
int subtract(int a, int b) {
return a - b;
}
int multiply(int a, int b) {
return a * b;
}
double divide(double a, double b) {
// 0 으로 나누기 확인
if (b == 0) {
return 0;
}
return a / b;
}
이 .cpp 파일에는 헤더 파일에 선언된 함수의 실제 구현이 포함되어 있습니다.
마지막으로 main.cpp를 만듭니다.
touch ~/project/main.cpp
main.cpp에 다음 코드를 추가합니다.
#include <iostream>
#include "math_functions.h"
int main() {
// 헤더 파일에서 함수 호출 시연
int x = 10, y = 5;
std::cout << "Addition: " << x << " + " << y << " = " << add(x, y) << std::endl;
std::cout << "Subtraction: " << x << " - " << y << " = " << subtract(x, y) << std::endl;
std::cout << "Multiplication: " << x << " * " << y << " = " << multiply(x, y) << std::endl;
std::cout << "Division: " << x << " / " << y << " = " << divide(x, y) << std::endl;
return 0;
}
이 main.cpp 파일은 math_functions.h 헤더 파일을 포함하여 함수 프로토타입을 사용할 수 있게 합니다. 그런 다음 math_functions.cpp에 구현된 함수를 사용할 수 있습니다.
여러 소스 파일을 사용하여 프로그램을 컴파일합니다.
g++ math_functions.cpp main.cpp -o math_operations
./math_operations
예시 출력:
Addition: 10 + 5 = 15
Subtraction: 10 - 5 = 5
Multiplication: 10 * 5 = 50
Division: 10 / 5 = 2
더 복잡한 헤더 파일로 다른 예제를 만들어 보겠습니다.
calculator.h를 만듭니다.
touch ~/project/calculator.h
calculator.h에 다음 코드를 추가합니다.
#ifndef CALCULATOR_H
#define CALCULATOR_H
class Calculator {
public:
// 계산기 연산을 위한 함수 프로토타입
int add(int a, int b);
int subtract(int a, int b);
int calculate(int a, int b, char operation);
};
#endif // CALCULATOR_H
이 헤더 파일은 Calculator라는 클래스와 해당 공개 메서드를 선언합니다.
calculator.cpp를 만듭니다.
touch ~/project/calculator.cpp
calculator.cpp에 다음 코드를 추가합니다.
#include "calculator.h"
int Calculator::add(int a, int b) {
return a + b;
}
int Calculator::subtract(int a, int b) {
return a - b;
}
int Calculator::calculate(int a, int b, char operation) {
switch (operation) {
case '+': return add(a, b);
case '-': return subtract(a, b);
default: return 0;
}
}
이 calculator.cpp는 calculator.h 헤더 파일에 선언된 메서드에 대한 구현을 제공합니다.
calculator_main.cpp를 만듭니다.
touch ~/project/calculator_main.cpp
calculator_main.cpp에 다음 코드를 추가합니다.
#include <iostream>
#include "calculator.h"
int main() {
Calculator calc;
std::cout << "Calculator Operations:" << std::endl;
std::cout << "10 + 5 = " << calc.calculate(10, 5, '+') << std::endl;
std::cout << "10 - 5 = " << calc.calculate(10, 5, '-') << std::endl;
return 0;
}
이 메인 파일은 Calculator 클래스를 사용하고 연산을 수행합니다.
계산기 프로그램을 컴파일합니다.
g++ calculator.cpp calculator_main.cpp -o calculator
./calculator
예시 출력:
Calculator Operations:
10 + 5 = 15
10 - 5 = 5
함수 프로토타입 및 헤더 파일에 대한 주요 사항:
- **헤더 파일 (.h)**은 함수 프로토타입, 클래스 및 기타 선언을 선언합니다. 인터페이스 역할을 하여 어떤 함수를 사용할 수 있는지 개략적으로 설명합니다.
- **소스 파일 (.cpp)**은 헤더 파일에 선언된 실제 함수를 구현합니다. 함수가 작동하는 방식에 대한 코드를 포함합니다.
#ifndef, #define, #endif (include guard) 는 동일한 헤더 파일의 중복 포함을 방지하여 잠재적인 컴파일 오류를 방지합니다.
- 헤더 파일을 사용하면 모듈화 및 코드 재사용성을 높일 수 있습니다.
- 헤더 파일을 사용하면 "무엇" (선언) 과 "어떻게" (구현) 를 분리할 수 있습니다.
- 코드 구성을 용이하게 하여 유지 관리 및 이해를 쉽게 합니다.
헤더 파일을 레스토랑 메뉴에 비유할 수 있습니다. 메뉴 (헤더) 는 무엇을 사용할 수 있는지 나열하고, 주방 (소스 파일) 은 실제 요리를 준비합니다.