Search code examples
c++visibilitynon-member-functions

Accessing non-member functions from another file


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.


Solution

  • 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();
    }