作为小白,刚开始看《C++程序设计 原理与实践 第二版》,第2章 Hello World
书中的经典程序很简要
// hello_world.cpp
#include "std_lib_facilities.h"
int main()
{
cout << "Hello, World!\n";
return 0;
}
笔者采用的是自带的clang编译器,于是直接在命令行中进行编译
clang -o hello_world hello_world.cpp
然后就是报错:未找到头文件std_lib_facilities.h
于是到网站www.stroustrup.com把头文件下载下来,放在与hello_world.cpp
同级目录中,于是再次编译
clang -o hello_world hello_world.cpp
发现还是报错:头文件中的代码使用了C++11的特性代码
于是修改编译命令,再次编译
clang -std=c++11 -stdlib=libc++ -o hello_world hello_world.cpp
发现还是报错:头文件中找不到ios_base
于是修改头文件中代码,将
//------------------------------------------------------------------------------
#if __GNUC__ && __GNUC__ < 5
inline ios_base& defaultfloat(ios_base& b) // to augment fixed and scientific as in C++11
{
b.setf(ios_base::fmtflags(0), ios_base::floatfield);
return b;
}
#endif
//------------------------------------------------------------------------------
改为
//------------------------------------------------------------------------------
#if __GNUC__ && __GNUC__ < 5
inline std::ios_base& defaultfloat(std::ios_base& b) // to augment fixed and scientific as in C++11
{
b.setf(std::ios_base::fmtflags(0), std::ios_base::floatfield);
return b;
}
#endif
//------------------------------------------------------------------------------
于是再次编译
clang -std=c++11 -stdlib=libc++ -o hello_world hello_world.cpp
发现还是报错:没有指定架构x86_64
于是修改命令行,再次编译
c++ -std=c++11 -stdlib=libc++ -o hello_world hello_world.cpp
编译成功。
花了一天时间,编写Hello World!
电脑上没有安装XCode,不过有安装最新版的eclipse,很可惜的是,eclipse在我没有修改头文件代码前也无法正常编译,于是我采用了命令行的编译方式。