g++ command line macro define byte stream

2020-05-09 03:32发布

I'm looking for the solution to define a byte stream as a macro from gcc/g++ command line via option -D, e.g. -Dxxx=byte_stream.

Below is the code snippet,

#ifndef MAGIC_BYTES
#define MAGIC_BYTES "\x01\x02\x00\x00\xa0\xb0"
#endif

I wish every time I can recompile the code without editing the source but using -DMAGIC_BYTES=xxx to define the byte stream.

I know to edit the source could be the solution, but just wonder how to define such byte stream from command line.

UPDATE,

I put the simple code below for this issue,

/* When
 * compile: gcc -o macro ./macro.c
 * output: 0x1, 0x2, 0x3, 0x4, 0x5,
 *
 * compile: gcc -o macro -DMAGIC_BYTES=\"\xa1\xa2\xa3\xa4\xa5\" ./macro.c
 * output: 0x78, 0x61, 0x31, 0x78, 0x61, 
 * but I expect 0xa1, 0xa2, 0xa3, 0xa4, 0xa5
 */
#include <stdio.h>

#ifndef MAGIC_BYTES
#define MAGIC_BYTES "\x01\x02\x03\x04\x05"
#endif

int main()
{
    char buf[] = { MAGIC_BYTES };
    for (int i = 0; i < 5; ++i)
        printf("%#x, ", buf[i]);
    printf("\n");
    return 0;
}

标签: c++ gcc macros g++ sh
1条回答
手持菜刀,她持情操
2楼-- · 2020-05-09 04:09

First this depends a lot from your environment, and the shell that you are using. For /bin/sh you could try something like

-DMAGIC_BYTES='"\x01\x02"'

that is escape the whole string with ''.

查看更多
登录 后发表回答