开发者

How to Replace only Part of the Variable using #define

#define C_TX_ TX_
#define C_RX_ RX_

enum Test
{
        C_TX_MAC = 0x0100, // Pre-Processor should replace C_TX_ to TX_
        C_RX_MAC = 0x0101  // But Not Working.
};

int main(int argc, char *argv[])
{
   开发者_如何学Python cout << TX_MAC; // HOW TO PRINT ?
    cout << RX_MAC; // HOW TO PRINT ?

    return true;

}


The pre-processor only operates on strings that are entire tokens. There would be chaos otherwise.

Try:

#define C_TX_MAC TX_MAC
#define C_RX_MAC RX_MAC


You cannot split a token with the pre-processor. You need to

#define C_RX_MAC RX_MAC
#define C_TX_MAC TX_MAC

(Of course there's ugly solutions such as adding a pre-pre-processing step:

sed s/C_ADDR_// x.cpp | g++ -x c++ -

But sed doesn't know about the context. It will replace strings e.g. cout << "And C_ADDR_RX = " with cout << "And RX = ".)


As stated in the other answers the pre-processor uses the whitespace to work out where the token is defined, and cannot replace it 'part way through". Perhaps you could try a "Find/Replace In Files" to rename the variables in your source code directly. Visual Studio's Find and Replace function can be used to replace any occurences in any folders/subfolders, or if you don't run with the Microsoft there's some other programs like NotePad++ that offer the same functionality. Both also support Regular Expressions for better targeted find/replace queries


The preprocessor replaces tokens, and C_TX_MAC is a full token.

However, you can achieve this fairly easily with some macro concatenation:

#include <iostream>
#define foo(x) C_ ## x

enum Test
{
        C_TX_MAC = 0x0100, // Pre-Processor should replace C_TX_ to TX_
        C_RX_MAC = 0x0101  // But Not Working.
};

int main()
{
   std::cout << foo(TX_MAC) << ' ' << foo(RX_MAC) << '\n';
}

(live demo)

Easy. No need for sed, and no need for find-and-replace in your text editor.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜