简体   繁体   English

如何正确地将同一个.h 文件包含在两个单独的.cpp 文件中?

[英]How to properly include the same .h file in two separate .cpp files?

I have a project consisting of 6 files;我有一个包含 6 个文件的项目; main.cpp , functions.h , tennisplayer.h , tennisplayer.cpp , tennisteam.h & tennisteam.cpp which are roughly defined as follows: main.cpp , functions.h , tennisplayer.h , tennisplayer.cpp , tennisteam.h & tennisteam.cpp大致定义如下:

// main.cpp

#include "tennisteam.h"
#include <iostream>
#include <string>
#include <exception>

// some main() code that needs functions.h definitions
// functions.h

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

#include "tennisplayer.h"
#include <iostream>
#include <string>
#include <limits>

// some constants & function definitions needed by both main.cpp & tennisteam.cpp

#endif
// tennisplayer.h

#ifndef TENNISPLAYER_H
#define TENNISPLAYER_H

#include <string>
#include <vector>

// tennisplayer class declarations

#endif
// tennisplayer.cpp

#include "tennisplayer.h"
#include <iostream>
#include <fstream>

// tennisplayer class definitions
// tennisteam.h

#ifndef TENNISTEAM_H
#define TENNISTEAM_H

#include "tennisplayer.h"
#include <string>
#include <vector>

// 

#endif
// tennisteam.cpp

#include "tennisteam.h"
#include <iostream>
#include <fstream>

// tennisteam class definitions

However, when I include functions.h into both main.cpp & tennisteam.cpp via tennisteam.h I get a linker error along the lines of:但是,当我通过tennisteam.hfunctions.h包含到main.cpptennisteam.cpp中时,我得到一个 linker 错误:

/usr/lib/gcc/x86_64-pc-cygwin/11/../../../../x86_64-pc-cygwin/bin/ld: /tmp/ccv30cX0.o:tennisteam.cpp:(.text+0x0): multiple definition of `function(std::string const&)'; /tmp/ccRThgpp.o:main.cpp:(.text+0x0): first defined here

I'm aware this is a linker error.我知道这是一个 linker 错误。 I've looked around for a fix but all I come across are posts instructing me to use include guards which I have done already.我四处寻找修复程序,但我遇到的只是指示我使用包括我已经完成的守卫的帖子。 Is there something I'm missing here?我在这里缺少什么吗? Any help would be appreciated.任何帮助,将不胜感激。

You have function function(std::string const&) that you not only declared but also defined in your header file.您有 function function(std::string const&) ,您不仅在 header 文件中声明了它,还定义了它。 If you need to have it defined there instead of a.cpp file, mark it as inline .如果您需要在那里定义它而不是 a.cpp 文件,请将其标记为inline

This results in two cpp files (namely main.cpp and tennisteam.cpp) ending up with a definition of that function, because they both include that header file.这导致两个 cpp 文件(即 main.cpp 和 tennisteam.cpp)以 function 的定义结束,因为它们都包含 header 文件。

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

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