首页 > 开发 > C++ > 正文

C++中变量、函数等名字中能不能含有$字符?

2017-09-11 21:35:01  来源: 网友分享

至少在我这里编译运行起来是没有问题的(g++ 4.8.1),但是在gdb调试的时候有如下状况。或者$在gdb中有什么含义吗?
代码

#include<cstdio>using namespace std;int $(int x) { return x; }int f(int x) { return x; }int main(){    return 0;}

gdb

Breakpoint 1, main () at test.cpp:99               return 0;(gdb) p f(4)$1 = 4(gdb) p $(4)Program received signal SIGSEGV, Segmentation fault.0x00000004 in ?? ()The program being debugged was signaled while in a function called from GDB.GDB remains in the frame where the signal was received.To change this behavior use "set unwindonsignal on".Evaluation of the expression containing the function(at 0x0x4) will be abandoned.When the function is done executing, GDB will silently stop.(gdb)

解决方案

p $(4)

这条命令的含义要这样解释:
$代表上一次的历史值,也就是4,,是f(4)这个函数调用的结果,这样就等同于:

p 4(4)

第一个4作为函数地址,第二个作为函数传入参数了,相当于:

p 0x4(4)

这样的一个函数调用,显然是非法的。

看了下gdb文档并测试下,这算是gdb和g++没协商好的地方。
由于C、C++不允许变量名含有$,所以gdb拉来做关键字了,导致gdb的print call等命令无法调用函数名为$的函数。break命令则是可以的。如果gdb不做修改的话,估计这个问题没法解决。

再看下这几条命令的结果能理解的更好一点:

###p f(7)$15 = 7###b $Note: breakpoint 4 also set at pc 0x400548.Breakpoint 6 at 0x400548: file strangersys.cpp, line 7.###b $(int)Note: breakpoints 2, 3 and 5 also set at pc 0x400533.Breakpoint 7 at 0x400533: file strangersys.cpp, line 4.###