我Dimension在一个文件Dimension.h中定义了一个类(比如我的所有类):
class Dimension
{
public:
constexpr Dimension() noexcept;
constexpr Dimension(int w, int h) noexcept;
int width;
int height;
};
Run Code Online (Sandbox Code Playgroud)
我认为我可以像在所有类中一样将定义放在一个单独的Dimension.cpp中:
#include "Dimension.h"
constexpr Dimension::Dimension() noexcept : width(0), height(0) {}
constexpr Dimension::Dimension(int w, int h) noexcept : width(w), height(h) {}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试使用该类时,编译器会告诉我:
警告:内联函数' constexpr Dimension::Dimension()'已使用但从未定义过
并在链接时:
未定义的引用' pong::graphics::Dimension::Dimension()'
(与其他构造函数相同)
如果我在标题中定义类,如下所示:
class Dimension
{
public:
constexpr Dimension() noexcept : width(0), height(0) {}
constexpr Dimension(int w, int h) noexcept : width(w), height(h) {}
int width;
int height;
};
Run Code Online (Sandbox Code Playgroud)
并省略.cpp文件,一切正常.
我正在使用GCC …
我可以constexpr在给出定义之前在 C++ 中声明一个函数吗?
考虑一个例子:
constexpr int foo(int);
constexpr int bar() { return foo(42); }
constexpr int foo(int) { return 1; }
static_assert(bar() == 1);
Run Code Online (Sandbox Code Playgroud)
实际上所有编译器都支持,demo:https : //gcc.godbolt.org/z/o4PThejso
但是如果foo在模板中转换函数:
constexpr int foo(auto);
constexpr int bar() { return foo(42); }
constexpr int foo(auto) { return 1; }
static_assert(bar() == 1);
Run Code Online (Sandbox Code Playgroud)
然后 Clang 拒绝接受它,说https://gcc.godbolt.org/z/EG7cG9KTM:
<source>:5:15: error: static_assert expression is not an integral constant expression
static_assert(bar() == 1);
^~~~~~~~~~
<source>:2:30: note: undefined function 'foo<int>' cannot be used …Run Code Online (Sandbox Code Playgroud) 当我尝试编译以下代码时,我得到一个链接器错误:Undefined symbols for architecture x86_64: "Foo()", referenced from: _main in main.o使用LLVM 4.2.
仅在标记函数时才会出现此问题constexpr.当标记功能时,程序会正确编译和链接const.为什么声明该函数constexpr会导致链接器错误?
(我意识到以这种方式编写函数不会带来编译时计算的好处;此时我很好奇为什么函数无法链接.)
main.cpp中
#include <iostream>
#include "test.hpp"
int main()
{
int bar = Foo();
std::cout << bar << std::endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
test.hpp
constexpr int Foo();
Run Code Online (Sandbox Code Playgroud)
TEST.CPP
#include "test.hpp"
constexpr int Foo()
{
return 42;
}
Run Code Online (Sandbox Code Playgroud)