c++ - 在另一个系统上构建时禁用特定的 C++ 行和#includes

标签 c++ eclipse gcc build makefile

我在我的项目中使用了 Google glog 日志记录系统。具体来说,我在代码的不同位置使用了以下类型的语句:

#include <glog/logging.h>
CHECK_EQ(foo,bar) << "Generic error message";
LOG(ERROR) << "Generic error message";
LOG(FATAL) << "Generic error message";

这个日志系统对于帮助我暂存和验证我的代码很重要。但是,有时我会将代码的生产运行外包给更大的服务器。这个大型生产服务器没有日志系统。 (我曾尝试在此生产服务器上构建日志系统,但遇到了问题。)

那么,假设我不能在生产服务器上使用日志系统,我该如何配置才能使日志命令在服务器上处于非事件状态?


在询问 SO 之前尝试自己解决这个问题,我尝试了以下...

在名为“globals.h”的现有头文件中,我定义了:

#ifdef NOGLOG
    #define MYLOG(i,m) std::cerr << #i << ": " << m
#else
    #include <glog/logging.h>
    #define MYLOG(i,m) LOG(i) << m
#endif

然后,我可以替换像 LOG(ERROR) << "ab" << x << "cd" 这样的代码与 MYLOG(ERROR,"ab" << x << "cd") .然后,当我使用类似 make all CUSTOM="-DNOGLOG" 的命令构建时,其中我的 gcc 编译语句设置了一个名为 $(CUSTOM) 的变量,glog 语句将不会被编译,而是简单的 std::cerr语句将被编译。

我在使用这种方法时遇到了两个问题:(1) 我不知道如何让 Eclipse IDE 插入 $(CUSTOM)进入 Eclipse 生成的 makefile 中的 gcc 编译语句; (2) 把 #include <glog/logging.h> #else 里面的语句body 导致了很多错误消息,如下所示。

In file included from /usr/include/errno.h:36,
                 from /usr/local/include/glog/logging.h:39,
                 from ../globals.h:23,
                 from ../COMPASS.h:11,
                 from ../COMPASS.cpp:13:
/usr/include/bits/errno.h: In function 'int* __errno_location()':
/usr/include/bits/errno.h:43: error: expected primary-expression before ',' token

注意: 目前,我只是注释掉了 CHECK_EQ打电话,我想一旦我弄清楚如何解决关于 LOG 的问题调用,我应该能够轻松地将解决方案扩展到 CHECK_EQ电话。

最佳答案

对于你的编译问题,

message << x << y无效。

你可以使用类似的东西:

// mystream.h

// class MyStreamImpl; // forward declaration for pimpl idiom if necessary

class MyStream
{
public:
    MyStream(int level);
    ~MyStream();

    MyStream& operator << (const char*);
    MyStream& operator << (int);
    // some other needed base type.
private:
    int level;
    // std::unique_ptr<MyStreamImpl> m_impl; // for pimpl idiom if necessary
};

MyStream MYLOG(int level) { return MyStream(level); }


// mylog.cpp


#ifdef NOGLOG
#include <iostream>

// implementation of all methods without glog

MyStream& MyStream::operator << (const char* message)
{
    std::cerr << message;
    return *this;
}

// other forwards to std::cerr

#else // NOGLOG

#include <glog/logging.h>

// implementation of all methods with glog

MyStream& MyStream::operator << (const char* message)
{
    Log(level) << message;
    return *this;
}

// other forwards to LOG()

#endif

关于c++ - 在另一个系统上构建时禁用特定的 C++ 行和#includes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18920068/

相关文章:

c++ - 从具有移动语义或返回值优化但不是复制构造函数的函数返回值

c++ - 空结构背后的目的?

如果网络被修改,Java 应用程序将挂起

c++ - GCC 7.X C++17 模板自动参数类型推导与枚举类错误

c - 为什么 volatile 适用于 setjmp/longjmp

c++ - 防止从 Dll C++ 注入(inject) Dll

eclipse - IntelliJ社区版等效于Ctrl-T eclipse,请转到方法

java - 在 Eclipse 中仅自动创建 getter

c++ - 使用 openssl 构建静态二进制文件的正确方法是什么?

c++ - 多次调用索引运算符的性能