在传递给C / C ++宏之前如何解析int变量? [英] How to resolve int variable before passing to C/C++ Macros?

查看:58
本文介绍了在传递给C / C ++宏之前如何解析int变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试执行以下代码:

I am trying to execute the following code:

#define channel1 10
#define channel(id) channel##id

int main(){
    int id = 1;
    cout << channel(id)<<"\n";

    return 0;
}

我收到以下错误:
错误:使用未声明的标识符'channelid'

相反,我希望输出为 10 ,如 channel(id)应该预处理为 channel1 ,并用10替换值。

Instead, I want an output to be 10, as channel(id) should be preprocessed to channel1 and which replaces the value with 10.

有什么方法可以实现?

推荐答案

问题是由于您试图混合使用在代码处理的不同阶段考虑到的信息。

The problem is caused because you're trying to mix information that it is considered at different stages in the processing of the code.

宏和所有CPP(C预处理器)都会发生(如其自身名称所示) )之前。它对变量值一无所知(最多,关于#define),并且它所做的大部分工作都是文本处理。

Macros and all CPP (C-Pre-Processor) stuff happens (as its own name indicates) before anything else. It doesn't know anything about the variable values (at most, about #define) and most of what it does is text wrangling.

某些变量值可能是在编译时已知(请参见 constexpr )...,但是其中大多数仅在运行时才知道。

Some of the variable values might be known at compile time (see constexpr) ... but most of them will only be known at run time.

因此,总而言之,您的代码会失败,因为预处理器对 id 变量。

So, in summary your code fails because the preprocessor knows nothing about the id variable.

编辑:解释求和示例。

我们有这段代码 x.cpp

#define sum(a,b) a + b

int main(int argc, char **argv) {
 int x = 1, y = 2;
 return sum(x,y);    
}

这段代码可以编译并正常工作。

And this code compiles and works fine.

让我们看看幕后发生的事情。

Let's look at what happens behind the scenes.

所有C / C ++源文件都经过了预处理。这意味着它们使用不同于C或C ++的语言进行评估:CPP(C预处理器)。这个CPP是所有#...内容的负责人(例如,搜索和包括头文件),正如我所说的,与C或C ++无关。

All C/C++ source files are preprocessed. This means that they are evaluated with a different language than either C or C++: the CPP (C-preprocessor). This CPP is the one responsible of all the #... stuff (for example searching and including the header files) and as I said, has nothing to do with C or C++.

实际上,您甚至可以在没有编译器的情况下运行它(尝试 cpp x.cpp ),或者您可以指示编译器仅执行此阶段( g ++ -o xi -E x.cpp

In fact, you can even run it without the compiler (try cpp x.cpp) or you can instruct the compiler to only execute this phase (g++ -o x.i -E x.cpp)

如果我们调查xi:

# 1 "x.cpp"
# 1 "<built-in>"
# 1 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 1 "<command-line>" 2
# 1 "x.cpp"


int main(int argc, char **argv) {
 int x = 1, y = 2;
 return x + y;

}

我们可以观察到以下几点:

We can observe several things:


  1. 还有许多附加的#行。编译器使用它们来跟踪所有内容的来源以及所包含位的来源,以便能够提供有意义的错误消息。

  2. 请注意如何在代码中替换我们的sum宏。盲目地执行此操作,结果字符串证明是错误的C / C ++语法,但只有在完成实际的C / C ++解析后,才能检测到该字符串。

这篇关于在传递给C / C ++宏之前如何解析int变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆