0

My code is supposed to work, I have checked for missing parenthesis and semicolon. And I also copied the code directly when watching a tutorial on Youtube. Still, I was not able to get it to work.

Main class

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

extern void myFunction(); // Initializing function from another class using extern keyword
int main()
{
    myFunction(); // calling the function
}

Another.h

#ifndef ANOTHER_H
#define ANOTHER_H

class Another
{

 public:
    void myFunction(); //Function prototype

};

#endif

Another.cpp

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

void Another::myFunction() // Function body
{
    std::cout << "This is a function from another source file." <<std::endl;
}

The error it is giving me is "undefined reference to myFunction()". Is it my compiler?

syafihakim
  • 81
  • 2
  • 10
  • @A.S.H Which part did i go wrong? – syafihakim Dec 03 '16 at 07:56
  • You have a member function of the class `Another` named `myFunction`. There is no `extern` function of that name. – R Sahu Dec 03 '16 at 07:57
  • You went wrong by confusing `class methods` with `non-class functions`. The former need an instance of the class to invoke the method upon it. :) – A.S.H Dec 03 '16 at 07:59
  • @A.S.H Ohh, the extern keyword does not work with class methods? Thanks for the clarification. – syafihakim Dec 03 '16 at 08:01
  • it's not a matter of *extern keyword*, You need to instantiate an `object` before invoking the class method: `Another a; a.myFunction();`. As for the *global, non-class-member* `myFunction()`, you just declared it but did not define it, so you cannot use it. – A.S.H Dec 03 '16 at 08:04
  • @A.S.H I used the extern keyword to avoid creating the object. I thought that is how the keyword works? After declaring it using the extern keyword could not I use it straight away without creating the object of Another? – syafihakim Dec 03 '16 at 08:08
  • No, the `extern` keyword is useless in this context. Its has a completely different meaning and usage. – A.S.H Dec 03 '16 at 08:09
  • @A.S.H oh really? thanks. I will go and look into the meaning right away. – syafihakim Dec 03 '16 at 09:25

0 Answers0