Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.4k views
in Technique[技术] by (71.8m points)

__cplusplus使用问题

某客时间大佬专栏,大佬写的代码

#ifdef __cplusplus                      // 定义了这个宏就是在用C++编译
    extern "C" {                        // 函数按照C的方式去处理
#endif
    void a_c_function(int a);
#ifdef __cplusplus                      // 检查是否是C++编译
    }                                   // extern "C" 结束
#endif

#if __cplusplus >= 201402                // 检查C++标准的版本号
    cout << "c++14 or later" << endl;    // 201402就是C++14
#elif __cplusplus >= 201103              // 检查C++标准的版本号
    cout << "c++11 or before" << endl;   // 201103是C++11
#else   // __cplusplus < 201103          // 199711是C++98
#   error "c++ is too old"               // 太低则预处理报错
#endif  // __cplusplus >= 201402         // 预处理语句结束

为何我编写demo老是报错呢?请各位大佬指出问题,出错最小demo附上:

#include <iostream>
using namespace std;

#if __cplusplus >= 201402 // 检查C++标准的版本号
    cout << "c++14 or later" << endl;    // 201402就是C++14
#elif __cplusplus >= 201103              // 检查C++标准的版本号
    cout << "c++11 or before" << endl;   // 201103是C++11
#else   // __cplusplus < 201103          // 199711是C++98
#   error "c++ is too old"               // 太低则预处理报错
#endif  // __cplusplus >= 201402         // 预处理束

int main()
{
    return 0;
}

[root c++]#g++ cplusplus.cc
cplusplus.cc:5:5: error: ‘cout’ does not name a type

 cout << "c++14 or later" << endl;    // 201402就是C++14
 ^~~~

包含了using namespace std,cout这里居然还是报错,及时修改成std::cout也报同样的错误,是我哪里没搞对,还是本来就不能这么用??预处理这里能这么用吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
cout << "c++14 or later" << endl;

你要写到函数体内,cpp 又不是脚本解释的。
你直接这样写全局里,不报错才怪。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...