早速、C++に久しぶり挑戦なのだが今までC++といえばMFCで単機能ツール作ったり、仕事ではPocketPC2002~2003で組み込みをやっていただけなのでピュアなC++を知らなかったりする。つまりC言語で言うstdio.hのiostream.hでガリガリ組んだ事ないのです。
今回はBSDサーバーなのでMFCとかのライブラリ無しで組むので少々敷居が高いかも知れませんが、パフォーマンスは出ると思います。
さてさて早速C++のコンパイルが可能かどうか確認をしてC++の再勉強をします。
C言語版Hello,world
> cat hello.c
#include
int main()
{
printf("Hello, world!\n");
return 0;
}
> cc hello.c
このBSDではgccとccは同一です。コンパイルは全く問題なし、次にC++版。コンパイルはg++にするとC++コンパイルオプション付きでgccを呼び出してくれます。
> cat hello.cpp
#include
int main()
{
cout << "Hello, world!" << endl;
return 0;
}
> g++ hello.cpp
In file included from /usr/include/c++/3.4/backward/iostream.h:31,
from hello.cpp:1:
/usr/include/c++/3.4/backward/backward_warning.h:32:2: warning: #warning This file includes at least one deprecated or antiquated header. Please consider using one of the 32 headers found in section 17.4.1.2 of the C++ standard. Examples include substituting the
おおっ一応コンパイルはされましたがヘッダの書き方で注意受けました。昔は.hつけても注意されなかったのにな~毎回注意が出るのも気持ちが悪いので
> g++ hello.cpp
hello.cpp: In function `int main()':
hello.cpp:5: error: `cout' undeclared (first use this function)
hello.cpp:5: error: (Each undeclared identifier is reported only once for each function it appears in.)
hello.cpp:5: error: `endl' undeclared (first use this function)
今度はエラーですか…。もしかするとネームスペースを定義してないから?まさかVC++みたいに仕様が厳格になったのか?#includeの直ぐ下にusing namespace std;を追加してみた。
> g++ hello.cpp
> ./a.out
Hello, world!
やっぱりそうなのか…。UNIXでCプログラミングは4年振りだけど結構厳格になったのね。当時はgccってバージョン2だったかなー。
Hello,world最終版はこちら
> cat hello.cpp
#include
using namespace std;
int main()
{
cout << "Hello, world!" << endl;
return 0;
}
因みにネームスペースを定義しないときはstd::coutのように記述すれば大丈夫です。
コメントする