DeffWHU 2019-08-06 13:21 采纳率: 0%
浏览 952
已结题

extern const / constexpr 定义问题

const 修饰的对象具有局部属性,一般将其定义在.c文件中,其他文件想访问的话就在.c对应的.h中extern一下。
那么:
application.c 如下:

#include <iostream>
#include "application.h"

constexpr int N_TEST = 10;

int 
func()
{
    int arra[N_TEST];
    std::cout << &N_TEST << std::endl;
    return 0;
}

application.h定义如下:

extern constexpr int N_TEST;

struct test_2{
    int arr[N_TEST];
};

编译报错:

test g++ ./test.cc ./application.cc -std=c++11
./test.cc:8:14: error: use of undeclared identifier 'N_TEST'
    int arrt[N_TEST];
             ^
1 error generated.
➜  test 

显示N_TEST未定义 将constexpr改为const也是报错。
问题:
1. 为什么会找不到定义
2. 此种情形N_TEST该怎么设计更合理,.h文件会使用其他.c中的const常量。

  • 写回答

2条回答 默认 最新

  • oyljerry 2019-08-06 13:48
    关注

    constexpr 不能支持extern

     int N_TEST = 10;
    
     extern int N_TEST;
    
    1 The constexpr specifier shall be applied only to the definition of a variable or variable template, the declaration of a function or function template, or the declaration of a static data member of a literal type (3.9). If any declaration of a function, function template, or variable template has a constexpr specifier, then all its declarations shall contain the constexpr specifier. [Note: An explicit specialization can differ from the template declaration with respect to the constexpr specifier. Function parameters cannot be declared constexpr. — end note ]
    
    评论

报告相同问题?

悬赏问题

  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 shape_predictor_68_face_landmarks.dat
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料