小编roy*_*uly的帖子

Why are global variables in x86-64 accessed relative to the instruction pointer?

I have tried to compile c code to assembly code using gcc -S -fasm foo.c. The c code declare global variable and variable in the main function as shown below:

int y=6;
int main()
{
        int x=4;
        x=x+y;
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

now I looked in the assembly code that has been generated from this C code and I saw, that the global variable y is stored using the value of the rip instruction pointer.

I thought that only const …

c compiler-construction assembly x86-64

4
推荐指数
2
解决办法
340
查看次数

在没有使用返回值的情况下,g++ 编译器是否将 constexpr 函数视为常规函数?

我试图查看由 g++ 编译的 cpp constexpr 函数的编译代码。我看到,如果该函数不返回任何内容,编译器将其视为常规函数,但如果它返回一个值并且我将此值分配给 constexpr 变量,则仅在编译时计算它。

代码示例:

constexpr int func(int x){
   return x!=0 ? 1: throw "Error";
}

int main(){
    func(2);
}
Run Code Online (Sandbox Code Playgroud)

和编译器输出:

push    rbp
mov     rbp, rsp
mov     edi, 2
call    func(int)
mov     eax, 0
pop     rbp
ret
Run Code Online (Sandbox Code Playgroud)

如您所见,它在运行时调用 func。相反,如果我将函数结果赋值给 constexpr:

constexpr int func(int x){
    return x!=0 ? 1: throw "Error";
}

int main(){
   constexpr int x = func(2);
}
Run Code Online (Sandbox Code Playgroud)

和编译器输出:

main:
    push    rbp
    mov     rbp, rsp
    mov     DWORD PTR [rbp-4], 1
    mov     eax, 0
    pop     rbp …
Run Code Online (Sandbox Code Playgroud)

c++ g++ constexpr

3
推荐指数
1
解决办法
54
查看次数

标签 统计

assembly ×1

c ×1

c++ ×1

compiler-construction ×1

constexpr ×1

g++ ×1

x86-64 ×1