Menu
CoddyTech

ヘッダーとリンケージ

Coddyの「C++開発者のためのC」コースのレッスン 18/48。

CとC++はどちらも、ヘッダーを使って翻訳単位をコンパイルします。Cのヘッダーには、C++のテンプレート、名前空間、オーバーロード、クラス宣言を含めることはできません。C++側でC APIを利用する場合、C言語のリンケージを指定するために、一般的にそのAPIをextern "C"で囲みます。

ヘッダーは、翻訳単位間で共有されるインターフェースを宣言します。インクルードガードは宣言の重複を防ぎ、定義はソースファイルに記述します。

C++の例

#include <iostream>
#include <iomanip>
#include <string>
#include <vector>
#include <array>
#include <map>
#include <memory>
#include <algorithm>
#include <functional>
#include <variant>
#include <sstream>
std::string bracket(const std::string& s){return "["+s+"]";}
int main(){
std::cout<<bracket("pen")<<"\n";
}

C++の出力:

[pen]

Cの例

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
static int total(int price,int count){return price*count;}
int main(void) {
printf("%d\n",total(3,4));
return 0;
}

Cの出力:

12
challenge icon

チャレンジ

簡単

lesson.h で宣言される公開関数 subtotal(price,count) を実装してください。必要であれば、lesson.c で非公開の static な multiply ヘルパーを使用してください。price と count の積を返してください。採点ではヘルパーの書き方ではなく、動作が確認されます。

ロックされていないソースファイルとヘッダーファイルを編集してください。これを直接呼び出す、表示されているロック済みの main.c と、宣言済みの公開 API の互換性を保ってください。別の main を追加しないでください。タスクで範囲が明示的に確認される場合を除き、すべての数値タスク用テストデータはオーバーフローを避けられるほど小さい値です。指定された出力だけを表示してください。入力解析と、表示されている場合は出力をドライバーが行います。

自分で試してみよう

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stddef.h>
#include <stdbool.h>
#include <limits.h>
#include <errno.h>
#include "lesson.h"
int main(void){int a=0,b=0;if(scanf("%d%d",&a,&b)!=2)return 1;printf("%d\n",subtotal(a,b));return 0;}
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

C++開発者のためのCのすべてのレッスン

自分で練習してみよう: Cオンラインコンパイラ