0

I have a header file with method names "Sample.h". I have imported this into another file, "methods.cpp" and wrote the code for all the methods in there. Now, I have a third file, "output.cpp" and want to use the methods that I defined in the methods file. Do I just import "Sample.h"?

2 Answers2

1

You've gotten a bunch of noise about include guards and the non-standard #pragma once; they have nothing to do with using the same header in multiple source files. They give you protection from multiple definition errors when you include the same header more than once in a single source file.

When you need to define functions in one source file and call them from another one, you put function prototypes in a header and include that header in both source files. Like this:

// function.h
#ifndef FUNCTION_H
#define FUNCTION_H
void f();
#endif // FUNCTION_H

// function.cpp
#include "function.h
#include <iostream>
void f() {
    std::cout << "Here I am.\n";
}

// user.cpp
#include "function.h"
int main() {
    f();
    return 0;
}
Pete Becker
  • 74,985
  • 8
  • 76
  • 165
-1

Yes but best to use something like:

#ifndef MY_SAMPLE__DOT__H__
#define MY_SAMPLE__DOT__H__

... rest of your header

#endif

This will guard against your code being unintentionally included more than once. This is good practice and you should use it all the time in all headers. Wrap all headers in these.

Alternatively use:

#pragma once

As suggested. It isn't standard so may not be supported. More about #pragma once

solarflare
  • 423
  • 3
  • 14
  • 4
    Note that the names used in this answer are reserved names. Do not actually use names like this for your include guards, your program will have undefined behavior. See also https://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier – Michael Kenzel Apr 02 '19 at 01:11
  • 1
    did you mean `#define`? – Serge Apr 02 '19 at 01:12
  • @MichaelKenzel I just put in what I thought would be random - you can call them what you like I guess. I wasnt aware of the reserved names recommendation, thanks. – solarflare Apr 02 '19 at 01:27
  • 2
    or use `#pragma once` on anything remotely modern. – Michael Dorgan Apr 02 '19 at 01:51
  • 1
    @MichaelDorgan good point, I havent used that since my Visual C++ days, never tried it on our pre-standard linux based legacy systems that I'm working on now, probably wouldnt work (and planes would literally fall out of the sky) – solarflare Apr 02 '19 at 02:16
  • This doesn't address the question. – Pete Becker Apr 02 '19 at 14:28