当使用多个文件时,我把预处理器命令放在哪里?

Where do I put preprocessor commands when using multiple files?

本文关键字:处理器 预处理 命令 在哪里 文件      更新时间:2023-10-16

我正在用c++为学校做一个项目,这个项目要分成多个文件。

test_driver.cpp - a file to test the code written
storage.cpp - implementation file for storage class and methods
storage.h - header file for storage
song.cpp - implementation file for song class, songs are the data type being manipulated by storage
song.h - header file for song

我把我的#include放在哪里?存储依赖于歌曲数据类型,因为它主要是操作它们,更改标题和移动它们等。如果这看起来像一个新问题,我很抱歉,但我真的不知道,也没有找到一个可靠的答案。我还想声明一个全局常数之间的实现文件共享,这是可能的吗?

我的观点是,每个头文件都应该可以包含,而程序员不必记住还要包含什么。这并不总是能够实现,但我认为这是一个很好的规则。

换句话说,如果"storage.h"需要在"song.h"中声明的内容,那么它应该包含"song.h"——这样,使用"storage.h"的人就不需要记住"song.h"的包含。

如果"storage.h"也使用了"fstream"中的内容,那么它应该包含"fstream"。

换句话说,如果在文件中包含"storage.h",那么使用"storage"类所需要做的就是这些。

试试这个(对于每个cpp文件,我列出了您应该包含在其中的h文件):

song.cpp
  song.h
storage.cpp
  storage.h
  song.h

或者,如果storage.h也依赖于song.h(即,它使用其中的定义),您可以这样做:

storage.h
  song.h
storage.cpp
  storage.h
对于常量,为什么不定义一个 呢?
constants.h

文件并在需要的地方包含它?