[英]How to properly include the same .h file in two separate .cpp files?
我有一個包含 6 個文件的項目; 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
但是,當我通過tennisteam.h
將functions.h
包含到main.cpp
和tennisteam.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
我知道這是一個 linker 錯誤。 我四處尋找修復程序,但我遇到的只是指示我使用包括我已經完成的守衛的帖子。 我在這里缺少什么嗎? 任何幫助,將不勝感激。
您有 function function(std::string const&)
,您不僅在 header 文件中聲明了它,還定義了它。 如果您需要在那里定義它而不是 a.cpp 文件,請將其標記為inline
。
這導致兩個 cpp 文件(即 main.cpp 和 tennisteam.cpp)以 function 的定義結束,因為它們都包含 header 文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.