0

I am wondering if it is possible to access non-member functions from another file. That is, a function declared and defined in a .cpp rather than in its header.

I have made a short example to show what I am asking about:

I have a very basic header file named Shape.hpp that just declares one function that will print the word “Square”

#ifndef SHAPE_HPP
#define SHAPE_HPP

class Shape
{
public:
    void printSquare();
};

#endif

In the Shape.cpp file, I define the printSquare() function, but I also declare and define a new function called printCircle()

#include “Shape.hpp”
#include <iostream>

void Shape::printSquare()
{
    std::cout << “Square”;
}

void printCircle()
{
    std::cout << “Circle”;
}

These files are trivial, but I am trying to show the question I have in a really simple way.

Now, in my Main.cpp file, I try to call both the printSquare() and the printCircle() methods.

#include “Shape.hpp”

int main()
{
    Shape shape;
    shape.printSquare();
    //shape.printCircle(); <—- this will give an error because printCircle() is not visible outside of Shape.cpp
}

Is there a way to allow my Main.cpp file to be able to use printCircle() without modifying my Shape.hpp or Shape.cpp files?

I am facing a very specific issue where I am writing tests for a class, but need to write tests for a non-member function.

bmb
  • 321
  • 1
  • 7
  • `printCircle()` is not a member of the `Shape` class so `shape.printCircle()` or `shape::printCircle()` make no sense. You need declare `void shape.printCircle()` somewhere that your translation unit can use it. – drescherjm Mar 11 '20 at 16:13

1 Answers1

2

Use the extern keyword, declare extern void printCircle() in the file you want to use it. It let the compiler know that the function is defined elsewhere.

#include “Shape.hpp”

extern void printCircle();

int main()
{
    // call extern function
    printCircle();

    Shape shape;
    shape.printSquare();
    printCircle();
}
YSC
  • 34,418
  • 7
  • 80
  • 129
noobius
  • 1,435
  • 5
  • 13
  • 1
    Note: `extern` is not necessary here, the default linkage of free functions is external already. – YSC Mar 11 '20 at 16:32
  • 1
    Even with the `extern` (or not) declaration, the `printCircle()` line will give an error, because `printCircle` is not a member of the `Shape` class. OP needs to have the `extern` declaration *and* change the commented-out line to: `printCircle()` (not `*shape*.printCircle()`). – Dave M. Mar 11 '20 at 16:35
  • Thanks! This is exactly what I needed. @YSC is right in saying extern is unnecessary, though. – bmb Mar 11 '20 at 16:36