我正在尝试在头文件中创建参数化静态数组。 让我详细说明我的要求
想在头文件中静态创建以下数组,可以在以下位置解析 编译时间
static char test_array[][256] = {
"hello_1",
"hello_2",
"hello_3" };
我需要使用宏生成此宏,该宏可以用%d代替1,2和3以及数字 参数的值也不固定。我的意思是明天该数组可以简单地通过头文件更改为
static char test_array[][256] = {
"hello_1",
"hello_45",
"hello_39",
"hello_101" };
我有在运行时在.c文件中执行此操作的代码,但我想通过宏在头文件中进行操作。
答案 0 :(得分:1)
最好的方法是编写生成器,它在编译时生成头数组。不久前,我编写了程序,可能会为您指明正确的方向:
/*
* Copyright (c) 2018 Krzysztof "Palaiologos" Szewczyk
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#define PERLINE 30
#define BUFSIZE 1024
static const char hexrange[] = "0123456789ABCDEF";
char buf[BUFSIZE];
int lineidx,line,i,bytes;
int main(int argc, const char * argv[]) {
FILE * in, * out;
if (argc != 4) {
fprintf(stderr, "Usage: %s infile outfile symbol\n", argv[0]);
return 1;
}
in = fopen(argv[1], "rb");
out = fopen(argv[2], "wb");
if (!in || !out) {
fputs("Could not open one of input files.\n", stderr);
return 1;
}
fprintf(out, "/* Generated by HexExport (by Krzysztof Szewczyk a.k.a. Palaiologos) */\n\n");
fprintf(out, "static const unsigned char %s[] = {", argv[3]);
while ((bytes = fread(buf, 1, sizeof(buf), in)) > 0) {
for (i = 0; i < bytes; ++i) {
int byte = ((uint8_t *)buf) [i];
if (lineidx++ == 0) {
if (line++)
fputc(',', out);
fputs("\n\t", out);
} else
fputs(", ", out);
fputs("0x", out);
fputc(hexrange[byte >> 4], out);
fputc(hexrange[byte & 0xF], out);
if (lineidx >= PERLINE)
lineidx = 0;
}
}
fputs("\n};\n", out);
fclose(in);
fclose(out);
return 0;
}
它的作用很简单,就是从文件生成十六进制数组。您可以对其进行修改以完成您的任务。使用宏生成这样的数组是不可能或非常艰巨的任务。源代码取自this place