ratzip ratzip - 7 months ago 72
C++ Question

undefined reference for the extern variable in C++ header

I have some code in C++:

// A.h
extern const char *names[3];

// B.cpp
#include "A.h"
const char *names[3] = {


void getName()
char *name;
strncpy(name, names[0], 5);

// C.cpp
#include "A.h"

Then when I build it, it generate the following error:

undefined reference to `names'
What is the reason and how to fix it?


You have some errors in the example, you provided, I assume you do not just copy/paste the source. Like the semicolon in line const char *names[3]; = {, or the missing comma in the list of strings next to "Name2"

So about your question. You should not include the A.h in you B.cpp, I mean the line #include "A.h" should be removed. You include the header file, and use the extern keyword only where you will use the *names pointer in other cpp files.