一般的常量在一个文件中定义后,在另外一个引用到这个变量的文件中在变量声明前加上extern即可,但是如果是常量,则需要在定义的地方也要加上extern,例如:
// ab.cpp : 定义控制台应用程序的入口点。
#include "stdafx.h"
#include<stdio.h>
extern const int m=10;
void main()
{
}
//b.cpp
#include <stdafx.h>
extern const int m;
void f()
{
int a=m;
}
以上程序编译没有错误。
但是要注意,外部extern const声明常量不能定义数组下标
如果在b.cpp中将int a=m;改为int a[m];编译报错:
error C2057: expected constant expression
error C2466: cannot allocate an array of constant size 0
error C2133: 'a' : unknown size
这时候不应该用常量了,用宏定义,#define m 10
转载于:https://blog.51cto.com/buptdtt/831623