在使用多个文件时,我在哪里放置预处理程序命令?

时间:2013-04-06 10:38:05

标签: c++ include c-preprocessor

我正在使用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

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

2 个答案:

答案 0 :(得分:1)

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

换句话说,如果“storage.h”需要在“song.h”中声明的内容,那么它应该包含“song.h” - 这样,任何使用“storage.h”的人都不需要记住包括“song.h”。

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

换句话说,如果在文件中包含“storage.h”,则只需使用“storage”类即可。

答案 1 :(得分:0)

试试这个(对于每个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

文件并将其包含在需要的位置?