错误:
main.cpp: In function 'constexpr int fib(int)':
main.cpp:6:42: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
return (n < sizeof(ftbl)/sizeof(*ftbl)) ? ftbl[n] : fib(n-2) + fib(n-1);
^
/tmp/cch0aLwI.o: In function `main':
main.cpp:(.text.startup+0xf): undefined reference to `std::cout'
main.cpp:(.text.startup+0x16): undefined reference to `std::ostream::operator<<(int)'
main.cpp:(.text.startup+0x2d): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::__ostream_insert<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*, long)'
main.cpp:(.text.startup+0x3c): undefined reference to `std::cout'
main.cpp:(.text.startup+0x43): undefined reference to `std::ostream::operator<<(int)'
main.cpp:(.text.startup+0x5a): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::__ostream_insert<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*, long)'
main.cpp:(.text.startup+0x69): undefined reference to `std::cout'
main.cpp:(.text.startup+0x70): undefined reference to `std::ostream::operator<<(int)'
main.cpp:(.text.startup+0x87): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::__ostream_insert<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*, long)'
/tmp/cch0aLwI.o: In function `_GLOBAL__sub_I_main':
main.cpp:(.text.startup+0xaa): undefined reference to `std::ios_base::Init::Init()'
main.cpp:(.text.startup+0xb9): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status
它在clang中执行没有问题。
该例子来自B.Stroustrup新书“TCPL”的第312页。
#include <iostream>
constexpr int ftbl[] { 1, 2, 3, 5, 8, 13 };
constexpr int fib(int n)
{
return (n < sizeof(ftbl)/sizeof(*ftbl)) ? ftbl[n] : fib(n-2) + fib(n-1);
}
int main()
{
std::cout << fib(1) << '\n';
std::cout << fib(2) << '\n';
std::cout << fib(6) << '\n';
}
编译器调用:gcc-4.8 -std=c++11 -O2 -pedantic -pthread -Wall main.cpp && ./a.out
答案 0 :(得分:5)
使用g++
代替gcc
。
或者,您可以根据需要链接标准库。由于链接顺序,你需要把它放在最后。
gcc-4.8 -x c++ -std=c++11 -O2 -pedantic -Wall -pthread main.cpp -lstdc++ && ./a.out