问题描述
我正在开发一种工业安全产品,需要非常快的启动时间。我试图遵循输出ASCII文件的行业标准。为了加快这个文件格式化步骤,我已经使用#define在静态内存中创建了几个字符数组。以下是一小部分例子:
I am working on a industry safety product that requires very fast startup time. I am trying to follow an industry standard for outputting an ASCII file. In order to speed up this file formatting step, I have used #define's to create several character arrays in static memory. Here's a small section for example:
#define COMTRADE_STATION_ID "Station Name,Device ID,1999\r\n"
#define COMTRADE_CHANNEL_COUNT "10,10A,0D\r\n"
#define COMTRADE_FREQUENCY "60\r\n"
#define COMTRADE_FILE_TYPE "BINARY\r\n1\r\n"
struct TS_ComtradeConfig
{
const char StationID[sizeof(COMTRADE_STATION_ID)];
const char ChannelCount[sizeof(COMTRADE_CHANNEL_COUNT)];
char Frequency[sizeof(COMTRADE_FREQUENCY)];
const char FileType[sizeof(COMTRADE_FILE_TYPE)];
};
TS_ComtradeConfig ConfigFile =
{
{COMTRADE_STATION_ID},
{COMTRADE_CHANNEL_COUNT},
{COMTRADE_FREQUENCY},
{COMTRADE_FILE_TYPE}
};
这里有一些我用来打印的基本代码。
And here's some basic code I've been using for printing it out.
for(int nIndex = 0; nIndex < sizeof(ConfigFile); nIndex++)
{
printf("%c", ((char*)(ConfigFile.StationID))[nIndex]);
}
这适用于生成静态字符数组,整个ConfigFile作为一个整体,但char数组是空终止,这意味着最终结果不符合行业标准。看来#define字符串是由预处理器空终止。有什么办法吗?
This works fine for generating the static char arrays, and it works fine for printing out the entire ConfigFile as a whole, but the char arrays are null-terminated, which means the end result does not meet the industry standard. It seems that the #define strings are being null-terminated by the pre-processor. Is there any way around this? Or any other methods for doing this sort of high speed operation?
推荐答案
如何进行字符串连接:
#define COMTRADE_STATION_ID "Station Name,Device ID,1999\r\n"
#define COMTRADE_CHANNEL_COUNT "10,10A,0D\r\n"
#define COMTRADE_FREQUENCY "60\r\n"
#define COMTRADE_FILE_TYPE "BINARY\r\n1\r\n"
#define COMTRADE_ALL COMTRADE_STATION_ID COMTRADE_CHANNEL_COUNT COMTRADE_FREQUENCY COMTRADE_FILE_TYPE
// no struct, plain char array, no intervening nulls (but a trailing one)
char[sizeof(COMTRADE_ALL)] comTradeAll = COMTRADE_ALL;
这篇关于#define在C ++中没有空终止的字符数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!