皆さんこんにちわ
お元気ですか。外は相変わらずの雪景色
さて、clangで詰まったエラーがあったのでご紹介
redefinition of 'add'
先日、一度定義されていますと掲載しましたが、こんな状況でも出るようです。
C++ファイル
diff.hpp
#include <iostream> int diff(int a,int b){ return a - b; }
add.hpp
#include <iostream> #include "./diff.hpp" int sum(int a,int b){ return a + b; }
test.cpp
#include <iostream> #include "./add.hpp" #include "./diff.hpp" int main(void){ int a = sum(2,3); int b = diff(3,2); return 0; }
Error
././diff.hpp:3:5: error: redefinition of 'diff' int diff(int a,int b){ ^ ././diff.hpp:3:5: note: previous definition is here int diff(int a,int b){ ^ test.cpp:6:10: error: use of undeclared identifier 'add' int a = add(2,3);
previous definition is here。前に定義されていますよと…。何がいいたいのかというと
この原因は2度同じヘッダーファイルが読まれていることが原因です。
つまり、同じファイルは一度しか読み込まなければいいのです。
いちいちファイルを管理するのはめんどくさい。そんな人にヘッダー部分に
#pragma once
と一文追加すれば大丈夫です。
C++ファイル
diff.hpp
#pragma once #include <iostream> int diff(int a,int b){ return a - b; }
add.hpp
#pragma once #include <iostream> #include "./diff.hpp" int sum(int a,int b){ return a + b; }
test.cpp
#include <iostream> #include "./add.hpp" #include "./diff.hpp" int main(void){ int a = sum(2,3); int b = diff(3,2); return 0; }
感想
結構規模の大きいC++のプログラムを書こうとするとやらかしそうなバグですね。
最近作ったのが大きくてつらい。