如何在C ++代码中使用Visual Studio宏 [英] How to use Visual Studio Macros within a C++ CODE

查看:85
本文介绍了如何在C ++代码中使用Visual Studio宏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用visual studio 2012,我已经为输出目录定义了一些宏,我想在我的C ++代码中使用它们,而不是像下面那样定义它们的绝对路径:

I am using visual studio 2012 and I have defined some macros for output directories,I want to use them in my C++ code instead of defining their absolute path like below :

char *path="C:/Dir/Release/FILE.txt"; 



我使用 ofstream 来刷新文本文件:


I am using ofstream to flush a text file:

void Func_ID_Out(vector<string>& s){	
        ofstream myfile;
	myfile.open(path);
	int len=s.size();
	for (int i=0;i<len;++i)
	{
		myfile<<s.at(i)<<" ID : "<<func_hashcode(s.at(i))<<"\n";
	}

	myfile.close();
}





而不是这样做我想使用预定义的 VS MACRO 作为输出目录以下功能的论点



instead of doing this I want to use predefined VS MACRO for output directory as a argument for the funtion below

myfile.open(PRE_DEFINED_MACRO/"FILE.txt")





是否有可能?有良好的机制吗?在我们的C ++代码体中使用Visual Studio宏?



Is it possible?Is there good mechanism to use Visual Studio Macros within our C++ Code body?

推荐答案

这对我有用。基本上,您将要使用字符串类轻松地将两个字符串添加到一起。如果你愿意,可以让 uniquePart 一个char *,除非你想弄乱c风格的字符串,你应该确保 path 是一个std :: string。



This works for me. Basically, you'll want to use the string class to easily add the two strings together. You can make uniquePart a char* if you like, but unless you want to get messy with c-style strings, you should ensure path is a std::string.

#include <iostream>
#include <fstream>
using namespace std;

#define definedVar "c:/"

//void someFunc(char *uniquePart)  // - this is fine too. Pick either.
void someFunc(string uniquePart)
{
    string path = definedVar;
    path += uniquePart;

    ofstream myFile;
    myFile.open(path.c_str());

    // do stuff with myFile here
    // 

    myFile.close();
}

int main()
{
    someFunc("/someFile.dat");
    return 0;
}


在我的脑海中,在C ++代码中使用VS宏的最佳方法是将VS宏与C ++相关联预处理器使用/ D命令行参数定义(属性 - > C ++ - >预处理器 - >预处理器定义)。



确保你有一个不错的默认值如果有人没有设置宏/外部定义命令行参数 - 没有什么比一个不正常的构建更糟糕的了,它会不小心把东西写在你硬盘上的奇怪地方。
Off the top of my head the best way of using a VS macro in C++ code would be to associate your VS macro with a C++ preprocessor define using the /D command line parameter (properties->C++->preprocessor->preprocessor definitions).

Just make sure you have a decent default if someone doesn't set up the macro/externally define the command line parameter - there's nothing worse than a badly behaved build that accidentally writes stuff in weird places on your hard disk.


这篇关于如何在C ++代码中使用Visual Studio宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆