user10538922
user10538922

Reputation:

When using headers, do I need to insert every function used in my cpp file?

If using my own files:

abc.cpp abc.h

Lets say abc.h contains:

//abc.h
#ifndef ABC_H
#define ABC_H

void function1 ();

#endif

Lets say abc.cpp contains:

//abc.cpp
void function1();
void function2();

void function1(){
function2();
}

void function2(){
}

If I want to access function2 by means of the code in function 1, Do I absolutely need to do this still:

//abc.h
#ifndef ABC_H
#define ABC_H

void function1 ();
void function2 ();

#endif   

Or can I just leave it like this:

//abc.h
#ifndef ABC_H
#define ABC_H

void function1 ();

#endif

Thanks in advance for any help. Andrew B

Upvotes: 1

Views: 229

Answers (1)

Alecto
Alecto

Reputation: 10740

The rule in C++ is declaration before use. This means that you have to declare that a function exists before it's used.

  • A declaration is just the signature of a function, for example: int add(int, int);
  • A definition is the body of the function. Definitions also act as a declaration, so if it wasn't previously declared, the definition is also the declaration.

This takes one of 3 forms:

  • You declare a function in the header file, and define it in the cpp file
  • You declare and define a function all at once
  • The function is an implementation detail, and it's declared and defined in the cpp file

Using cpp-file only functions

These functions aren't visible outside of the cpp file they're defined in:

// foo.hpp

// Declaration
void foo();
// foo.cpp

// Definition
void do_some_stuff() {
    std::cout << "Hello, world!\n";
}
// Definition
void foo() {
    do_some_stuff();
}

Header-only functions

Because C++ uses textual inclusion for header files, you can have functions defined in the header file, and they can access functions defined in the cpp file as long as the declaration comes first:

// example.hpp

// declaration comes before usage
void printMessage(); //Defined in Cpp file

void printMessage10x() {
    for(int i = 0; i < 10; i++) {
        printMessage();
    }
}
// example.cpp
void printMessage() {
    std::cout << "Hello, world!\n";
}

This works because the declaration for printMessage occurs earlier in the header file, so it's visible to the compiler.

Are there uses for declaring a function in the header file?

Functions declared in a header file can be inlined without having to resort to Link-time Optimization. In addition, there's more information availible to the compiler when it's considering whether or not to inline the function.

Additionally, templated classes and functions are easiest to use when they're declared within the header file. See this question for more information.

// min.hpp

// Calculates the minimum of two numbers of any type
template<class T>
T min(T a, T b) {
    if(a < b) 
        return a;
    else 
        return b;
}

Upvotes: 1

Related Questions