Reputation: 1
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?
Upvotes: 0
Views: 96
Reputation: 3433
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);
}
Upvotes: 1