小编MiC*_*iCo的帖子

constexpr 函数在多个模块中共享

当我使用 constexpr 函数时,我注意到一个奇怪的行为。我将代码简化为一个简化的示例。从两个不同的翻译单元(模块 A 和 B)调用两个函数。

#include <iostream>

int mod_a();
int mod_b();

int main()
{
    std::cout << "mod_a(): " << mod_a() << "\n";
    std::cout << "mod_b(): " << mod_b() << "\n";
    std::cout << std::endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

这些模块看起来很相似。这是mod_a.cpp:

constexpr int X = 3;
constexpr int Y = 4;

#include "common.h"

int mod_a()
{
    return get_product();
}
Run Code Online (Sandbox Code Playgroud)

只有一些内部常数不同。这是mod_b.cpp:

constexpr int X = 6;
constexpr int Y = 7;

#include "common.h"

int mod_b()
{
    return get_product();
}
Run Code Online (Sandbox Code Playgroud)

constexpr两个模块都使用“common.h”中定义的通用函数:

/* static */ …
Run Code Online (Sandbox Code Playgroud)

c++ translation-unit constexpr-function

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

标签 统计

c++ ×1

constexpr-function ×1

translation-unit ×1