gccコマンドでC++のコードをコンパイルする。

gccコマンドでC++のコードをコンパイルする。

そんなことしたくないですが……。

TAがC++で出したコードをCのコードだと思ってgccでビルドしたぽくて文句を言ってきた。

hello.cpp
Copied!
#include <iostream>

int main(int, char**) {
std::cout << "Hello, World!" << std::endl;
}
試しにこのコードを gcc hello.cpp ( g++ hello.cpp ではなく)してみる。
out
Copied!
$ gcc hello.cpp
/usr/bin/ld: /tmp/cczEiB7v.o: in function `main':
hello.cpp:(.text+0x1d): undefined reference to `std::cout'
/usr/bin/ld: hello.cpp:(.text+0x22): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)'
/usr/bin/ld: hello.cpp:(.text+0x2c): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)'
/usr/bin/ld: hello.cpp:(.text+0x37): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))'
/usr/bin/ld: /tmp/cczEiB7v.o: in function `__static_initialization_and_destruction_0(int, int)':
hello.cpp:(.text+0x6b): undefined reference to `std::ios_base::Init::Init()'
/usr/bin/ld: hello.cpp:(.text+0x80): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status
ldでコケてる。正直もっと無理だと思っていた(1行目の #include <iostream> で「そんなファイル無い」って言われるぐらいかと思ってた)。
これ結構行けそうじゃない? と思って、 gcc hello.cpp -c する。通る。普通に hello.o できるじゃん。
↑のldの文句を眺めてると、libstdc++のことを知らないだけっぽいので、 gcc hello.o -o hello -Wl,-lstdc++ してみると普通に hello できた。
out2
Copied!
$ ./hello
Hello, World!
へーまじか……おもしろ……となったのでここにめも。

windowsだと cl.exe でどっちもコンパイルできるらしいぺこ。

にこの挙動が書かれてる って反応をもらって「ほんとだ〜」って言った。

Powered by Helpfeel