DEV Community

Discussion on: How to use multiple files in C++

Collapse
codemouse92 profile image
Jason C. McDonald • Edited on

As a rule, I always use *.hpp for C++ header files. It's not uncommon to find a mixture of C and C++ within a repository, and the difference in filename helps clarify that.

To put that another way:

  • *.h: C header file
  • *.c: C implementation file
  • *.hpp: C++ header file
  • *.cpp: C++ implementation file

See how clear that is?

Building on that, once you start including multiple files in your project, you should have some sort of directory structure. Here is what I use; it's far from the only way to do it, but in my experience, it seems to be one of the most effective.

project/
├── main.cpp
├── Makefile
├── include/
│   ├── classy.hpp
└── src/
    └── classy.cpp
Enter fullscreen mode Exit fullscreen mode

As a last note, use Makefiles for building most simple projects. However, as soon as you get into anything more complicated, take a look at CMake (instead of Autotools, which is far harder to learn).

Collapse
lilyyanglt profile image
Lily

Hi Jason! Is there any good resources you'd recommend on creating makefiles? I just learned about this today and I am fascinated by it! However, based on your suggested structure for a project, I don't know really know how to write rules in the makefile for grabbing files that are in include and src.
Any suggestion would be greatly appreciated! I am a beginner in c++.
Lily

Collapse
codemouse92 profile image
Jason C. McDonald • Edited on

Afraid I don't have anything formal. I've kinda figured out Makefiles by experimentation and fragments of examples over the years.

If you want, you can take a look at MousePaw Media's documentation on our C/C++ build system, which combines CMake and Makefiles. The system is a bit unconventional, but it works extraordinarily well.

mousepawmedia.net/rmd/buildsystem/...

NOTE: The information on that link is a draft, and is subject to change.

Thread Thread
lilyyanglt profile image
Lily

Thank you for the reply Jason!! Really appreciated! I'll take a look at what you suggested :)