简体   繁体   English

在c ++中的两个文件上使用标头?

[英]Using a header on two files in c++?

I have a header file with method names "Sample.h". 我有一个方法名称为“Sample.h”的头文件。 I have imported this into another file, "methods.cpp" and wrote the code for all the methods in there. 我已将其导入另一个文件“methods.cpp”并编写了所有方法的代码。 Now, I have a third file, "output.cpp" and want to use the methods that I defined in the methods file. 现在,我有第三个文件“output.cpp”,并希望使用我在方法文件中定义的方法。 Do I just import "Sample.h"? 我只是导入“Sample.h”吗?

You've gotten a bunch of noise about include guards and the non-standard #pragma once ; 关于包括警卫和非标准#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;
}

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 更多关于#pragma一次

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM