2

I am really new in C++, and I can not solve the compilation error below.

data_structure.h

#include <stdint.h>
#include <list>

namespace A {

        class B {
            public:

            bool        func_init(); // init
            };

};

data_structure.cpp

#include "data_structure.h"

using namespace A;

bool B::func_init(){

    std::cout << "test init" << std::endl;
    return true;

}

main.cpp

#include    <iostream>
#include    "data_structure.h"

using namespace A;

int main( int argc, char **argv ) {

    A::B s;
    s.func_init();

    return 0;
}

I have an error as the following

undefined reference to `A::B::func_init()'

Please kindly advice why I can not get the func_init, eventhough it is declared as public? I have put also the correct namespace there.

Would appreciate for any response.

xambo
  • 399
  • 2
  • 4
  • 17

4 Answers4

5

That's a linker error, so you're probably not compiling all your source files, or linking them together, or making some weird use of the C compiler (I see your files have the extension .c, some compilers treat them as C-source).

Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
2

g++ main.cpp data_structure.cpp -o test should do it.

However I did need to add #include <iostream> to your data_structure.cpp file to resolve

data_structure.cpp: In member function ‘bool A::B::func_init()’:
data_structure.cpp:7:5: error: ‘cout’ is not a member of ‘std’
data_structure.cpp:7:33: error: ‘endl’ is not a member of ‘std’

and make it compile.

batfan47
  • 97
  • 1
  • 6
1

The definition of a function has to be in the namespace that declares the function. A using declaration just pulls in names from the namespace; it doesn't put you inside it. So you have to write data_structure.cpp like this:

#include "data_structure.h"
#include <iostream>

namespace A {
bool B::func_init() {
    std::cout << "test init" << std::endl;
    return true;
}
}

Or, if you prefer, you can use the namespace name explicitly in the function definition:

bool A::B::func_init() {
    std::cout << "test init" << std::endl;
    return true;
}
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • +1 That was my understanding, although I did manage to compile code equivalent to OP's using g++ 4.4.3, which I really wasn't expecting to work. – juanchopanza Apr 10 '13 at 15:26
0

Have you tried not putting

using namespace A;

in your data_structure.cpp file and instead putting:

#include "data_structure.h"

bool A::B::func_init() {
   std::cout << "test init" << std::endl;
   return true;
}

I have the feeling that when you use using namespace A; doesn't let you append function definitions to the namespace, but only tells the compiler/linker where to look for Types or Functions...

Another theory: Have you tried nesting your CPP code in the same namespace?

#include "data_structure.h"

namespace A {
   bool B::func_init() {
      std::cout << "test init" << std::endl;
      return true;
   }
}
SsJVasto
  • 486
  • 2
  • 13