g++ command line macro define byte stream

自闭症网瘾萝莉.ら 提交于 2019-12-02 15:47:51

问题


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;
}

回答1:


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 ''.



来源:https://stackoverflow.com/questions/46793288/g-command-line-macro-define-byte-stream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!