One difference about `const` in C&C++

The const qualifier has one fatally important difference between C and C++ about linkage that may cause a failure of compiling.

Although it is often said that C++ is a superset of C, which means that a correct C program is also a correct C++ program, in most cases. But they still have some differences that may crash your compiling occasionally. Here I found one to share with you.

Read these two C source files:

// main.c
#include <stdio.h>
extern const int a;
int main(){
    printf("%d\n", a);
    return 0;
}
// ext.c
const int a = 42;

And compile them with $ gcc -o main ext.c main.c.

And these two “the same” C++ source files:

// main.cpp
#include <iostream>
extern const int a;
int main(){
    std::cout << a << std::endl;
    return 0;
}
// ext.cpp
const int a = 42;

And compile them with $ g++ -o main ext.cpp main.cpp.

Difference

The compiler will complain undefined reference to 'a' and fail to link when compiling the C++ project. The reason is that in C++, the const object are local to a file by default! That means a in ext.cpp has an internal linkage while a in ext.c has an external linkage.

So you should explictly add an extern before const int a = 12; in the C++ file.

Epilogue

It’s confusing and ugly that they are different in C and C++, at least in my opinion. I don’t know why it is designed like this. Maybe it’s historical reason? It’ll be appreaciated if anyone who know the reason of that email me to msn4399@163.com.


© 2017-2018. All rights reserved.