0
votes

Have searched enough answers but none of the solutions work for me.

scenario : I am trying to include a .h file that has some functions declared (not defined) and some variables declared.

If I include this header file in the source files (2 to be precise) that actually use the functions and variables, then the last one that compiles has a linker error that states

undefined reference to `abc::myfun(char const*, char const*, char*)'

All the functions and variables in the header files have been declared as extern and include guards are present.

I wish to have one cpp file put a value in the variable defined in the .h file and another cpp file to be able to read it.

Also if it helps, every piece of my code is in a namespace that I have defined ( namespace abc{ //all my code, in all the files } )

2
First, does at least one source file define the variable/function? Are you including that in the link? Second, do you include your headers outside of the namespace? You don't want to inadvertently nest - ie abc::abc::somethingpaddy
specifically abc::myfun(char const*, char const*, char*) as noted from your error seems to be at least one culprit. Could you posted the declaration from your header file and where it is defined in a source file?MartyE

2 Answers

3
votes

Declarations in your .h file are doing exactly that - letting compiler know of the objects you are planning on declaring "somewhere". That "somewhere" would be a compilation unit (a .c or .cpp file) where that variable would be defined.

Here's an example (skipping the guards for simplicity):

foo.h:

extern int global_foo;

foo.c:

#include "foo.h"
int global_foo; // optionally you can initialize like this: int global_foo = 123;

main.c:

#include "foo.h"
void bar()
{
  global_foo = 0; // accessing that variable which is "outside" of this file

As paddy mentioned above - make sure you are not accidentally nesting namespaces, since abc::something is not the same as abc::abc::something

0
votes

Your error seems to be with abc::myfun(char const*, char const*, char*). I was able to reproduce and confirm this. Without the second part you'll get the error.

I'm guessing you have a header file something like

namespace abc 
{
    void myfun(char const* p1, char const* p2, char* p3);
}

and a .cpp source file needs

namespace abc
{
    void myfun(char const* p1, char const* p2, char* p3)
    {
        // do fun stuff
    }
}