0

Are header files able to call functions from other header files. And if so how do you do this. For example:

void IntStack::push(int n)
{
    IntNode *newNode = new IntNode(n);
    newNode->next = top;
    top = newNode;
    return;
}

Would i be able to create another header file and be able to use this push function?

1
  • #include copies the contents of the file in that file while running compile. So the answer is yes. But usually code isn’t in headers and may cause problems with multiple copies etc. Would be better to not have it in a header Commented Oct 12, 2019 at 4:39

1 Answer 1

1

You can do this (however you probably don't want to, at least not for the example you link - see below).

First, here's how you could do what you asked:

// a.hpp
#pragma once // or include guards if you can't use pragma once
class IntStack {
    ...
    void push(int n);
    ...

// b.hpp
#pragma once // or include guards if you can't use pragma once
#include "a.hpp"
void foo() { IntStack i; i.push(0); }

However, you probably don't want to do this. Including headers in other headers can bloat compilation times and is just generally not necessary. What you want to do is have the declarations for your classes, types and functions in header files, and then have the various definitions in cpp files.

For your example:

// a.hpp
#pragma once // or include guards if you can't use pragma once
class IntStack {
    ...
    void push(int n);
    ...

// a.cpp
#include "a.hpp"

void IntStack::push(int n) {
    IntNode *newNode = new IntNode(n);
    newNode->next = top;
    top = newNode;
    return;
}

// b.hpp
#pragma once // or include guards if you can't use pragma once
void foo();

// b.cpp
void foo() {
    IntStack i;
    i.push(0);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.