将#define存储为std :: string的C ++将大小作为零编译时间

时间:2013-08-12 11:32:25

标签: c++

我是C ++的新手,遇到了奇怪的问题。我有一个#define   在common.h中

 #define TEXT_VALUE "Alpha"

在program.cpp中的一个方法中,我想访问它并想要做类似下面的事情

 #include common.h

 void TestProgram::TestProgram(){
   std::string test_value = TEXT_VALUE;

   if(test_value.empty()) {//check during compile time if not set then set to default
      test_value = "Beta";
   }
 }

但是test_value总是在生成的可执行文件中设置为“Beta”...即使common.h具有#define ....

如果上述方法不正确,那么......还有其他选择吗?

代码在MAC上工作正常但在Windows上没有使用Visual Studio 2005(无法升级:-()

2 个答案:

答案 0 :(得分:2)

要在编译时检查,请使用预处理器进行测试;)

    //common.h
    #define TEXT_VALUE "Alpha"
    //...

    //somwhere
    #ifdef TEXT_VALUE
    std::string test_value = TEXT_VALUE;
    #else
    std::string test_value = "Beta";
    #endif

答案 1 :(得分:0)

#include <iostream>
#include "common.h"
std::string test_value = TEXT_VALUE;
using namespace std;
int main(int argc, char const *argv[])
{
    if(test_value.empty()) 
    {//check during compile time if not set then set to default
           test_value = "Beta";
    }
    cout<<test_value;
    return 0;
}

以上代码适用于我。