22

I have a strange problem when I create a static function in class A and I want to call it from class B function. I get

undefined reference to `A::funcA(int)'

Here is my source code : a.cpp

#include "a.h"

void funcA(int i) {
    std::cout << i << std::endl;
}

a.h

#ifndef A_H
#define A_H

#include <iostream>

class A
{
    public:
        A();
        static void funcA( int i );
};

#endif // A_H

b.cpp

#include "b.h"

void B::funcB(){
    A::funcA(5);
}

and b.h

#ifndef B_H
#define B_H
#include "a.h"

class B
{
    public:
        B();
        void funcB();
};

#endif // B_H

I'm compiling with Code::Blocks.

xenom
  • 377
  • 1
  • 5
  • 15

2 Answers2

36
#include "a.h"

void funcA(int i) {
    std::cout << i << std::endl;
}

should be

#include "a.h"

void A::funcA(int i) {
    std::cout << i << std::endl;
}

Since funcA is a static function of your class A. This rule applies both to static and non-static methods.

Nbr44
  • 2,042
  • 13
  • 15
  • Thanks, it's exactly the problem.. I thought that as funcA() was static, writing A::funcA() would not have any sense... It seems I'm wrong. – xenom Jul 18 '13 at 15:32
7

You forgot to prefix the definition with the class name :

#include "a.h"

void A::funcA(int i) {
     ^^^
//Add the class name before the function name
    std::cout << i << std::endl;
}

The way you did things, you defined an unrelated funcA(), ending up with two functions (namely A::funcA() and funcA(), the former being undefined).

JBL
  • 12,588
  • 4
  • 53
  • 84
  • 1
    Thanks, it was the problem. As Nbr44 answered the first I'm gonna validate his answer but upvote yours. – xenom Jul 18 '13 at 15:42