헤더와 링크
Coddy의 Kotlin 개발자를 위한 C++ 코스 레슨. 48개 중 29번째.
Kotlin에는 헤더가 없습니다. 컴파일러는 모듈의 모든 소스 파일을 함께 읽으며, import는 정규화된 이름을 짧게 쓸 수 있게 할 뿐입니다. C++ 컴파일과 링크에는 헤더와 정의가 필요합니다. C++는 구현 파일을 각각 컴파일한 다음 링크합니다. 헤더는 선언을 공유하며, 인클루드 가드는 하나의 번역 단위 안에서 중복을 방지합니다.
Kotlin
import kotlin.math.floor as down
fun main() {
println(down(2.7).toInt())
println(kotlin.math.ceil(2.1))
}
C++
#include <iostream>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <set>
#include <algorithm>
#include <memory>
#include <sstream>
#include <stdexcept>
#include <utility>
namespace labels {std::string bracket(const std::string& s){return "["+s+"]";}}
int main(){
std::cout<<labels::bracket("ready")<<"\n";
}
각 프로그램의 실행 과정을 독립적으로 추적하세요. 이 예제들은 과제와 다른 연산이나 데이터를 사용해 개념을 보여 줍니다. 소스와 대상의 출력이 일치한다고 가정하지 마세요.
챌린지
쉬움입력: 음이 아닌 정수 두 개이며, 둘 다 0은 아닙니다. 최대공약수를 exercise.cpp에 구현하고 헤더에 선언하세요.
exercise.hpp와 exercise.cpp에 선언된 API를 구현하세요. 두 파일 모두 편집할 수 있으며, 공개 시그니처를 유지하세요. 잠금된 main.cpp는 표준 입력을 읽고 API를 직접 호출합니다. 명시된 경우 공개 API 동작도 별도로 확인합니다. API 내부에서 출력하지 말고 값을 반환하세요. 정수 입력값과 결과는 부호 있는 int에 들어가며, 별도의 언급이 없는 한 텍스트는 ASCII입니다.
직접 해보기
#include "exercise.hpp"
#include <iostream>
int main(){
std::vector<std::string> rows; std::string line; while(std::getline(std::cin,line)) rows.push_back(line);
std::istringstream in(rows.empty()?"":rows[0]);int a,b;in>>a>>b;std::cout<<gcd(a,b)<<"\n";
}
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
Kotlin 개발자를 위한 C++의 모든 레슨
직접 연습해 보세요: 온라인 C++ 컴파일러