Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

undefined reference to a static function

Tags:

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.

like image 959
xenom Avatar asked Jul 18 '13 15:07

xenom


People also ask

What is undefined reference to function in c?

An “Undefined Reference” error occurs when we have a reference to object name (class, function, variable, etc.) in our program and the linker cannot find its definition when it tries to search for it in all the linked object files and libraries.

What is a static function in C++ with example?

The static member functions are special functions used to access the static data members or other static member functions. A member function is defined using the static keyword. A static member function shares the single copy of the member function to any number of the class' objects.

What is undefined symbol error in c++?

A symbol remains undefined when a symbol reference in a relocatable object is never matched to a symbol definition. Similarly, if a shared object is used to create a dynamic executable and leaves an unresolved symbol definition, an undefined symbol error results.

Can static function use non static members?

A static method can access only static members and can not access non-static members. A non-static method can access both static as well as non-static members.


2 Answers

#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.

like image 180
Nbr44 Avatar answered Oct 15 '22 17:10

Nbr44


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).

like image 43
JBL Avatar answered Oct 15 '22 17:10

JBL