2021年5月31日月曜日

c言語でのヘッダファイル重複読込防止はpragma onceが便利


c言語でヘッダファイルの重複定義をする際、自分は下記のように「ifndefとdefine」を駆使して重複読込防止(インクルードガード)をしてきました。
#ifndef _SAMPLE_LIB_H_
#define _SAMPLE_LIB_H_

class SampleLib {
int id;
};

#endif

他の方が作ったライブラリを参考に眺めていたら、見慣れない「pragma once」という記述と「ifndefとdefine」が無いヘッダファイルを見つけました。
#pragma once

class SampleLib {
int id;
};

「pragma once」は「ifndefとdefine」で重複防止をしなくて良いように、標準ではないもののc系のコンパイラで機能する記述のようです。

pragma once - Wikipedia より抜粋
In the C and C++ programming languages, pragma once is a non-standard but widely supported preprocessor directive designed to cause the current source file to be included only once in a single compilation.

Arduino IDE(avr gcc)でも機能しました。
条件: Ver1.8.13、Arduino Uno向けのビルド


pragma onceを使うと、記述量が減り、ヘッダファイルをコピーしてファイルを作る際にifndefのマクロ名の書き換え忘れによるエラーに時間を取られなくなるのが嬉しいです。

0 件のコメント :