2

I have some code in C++:

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

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

   "Name1",
   "Name2"
   "Name3"
};

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?

ratzip
  • 1,571
  • 7
  • 28
  • 53

2 Answers2

1

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.

matt2405
  • 171
  • 2
  • 13
0

B.cpp shouldn't include A.h There's no need. The extern in A.h is a declaration that sets an expectation for the linker that a global variable can be found in another object file that's to be linked, but B.cpp is where the variable is defined.

Just make sure to link both A.cpp and B.cpp at link time.

Component 10
  • 10,247
  • 7
  • 47
  • 64
  • Including the header ensures that any mismatch in the declarations gets reported at compile time, which seems useful. – Alan Stokes May 05 '15 at 09:59
  • Point taken. I've always avoided it for the reason above and because it seemed a bit misleading if you're declaring something `extern` and defining it in the same compilation unit, but I see where you're coming from. – Component 10 May 05 '15 at 10:22