Skip to content
Advertisement

Compiling simple C++ projects using make [closed]

I want to switch completely from using Windows to Linux (Ubuntu). Last issue that prevents me from transition is necessity to code in C++. On Windows I use Visual Studio. On Linux, I am currently struggling with understanding how make works.

I need set of simple instructions and tips. Provided I have five files: main.cpp, BuisnessCard.h, BuisnessCard.cpp, Tell.h, Tell.cpp. Please, tell me, how to create Makefile, so it will complete following tasks for me:
1) When I type make main I’d like it to create “executable” file ./main, which will include code from BuisnessCard.h and Tell.h (and of course. according .cpp files).
2) When I type make main_debug, it’ll perform same action, but with different compile options (called flags?)

Could anyone answer my questions or provide links to elemental tutorials? I have already tried: MRBook’s tutorial and this SO post, but it is a bit too advanced already, while I don’t seem to get the basics.

Advertisement

Answer

If you are interested in make, I recommend reading this introduction to GNU make. Here’s a simple (and not very robust) example of a makefile for your program:

main: main.cpp BuisnessCard.h BuisnessCard.cpp Tell.h Tell.cpp
    c++ $^

Although knowing the basics of make may be useful, I’d recommend using a more high-level tool such as CMake to manage your build configuration. Here’s a similar CMake config:

project(MYPROJECT)
add_executable(main main.cpp BuisnessCard.h BuisnessCard.cpp Tell.h Tell.cpp)

The advantage of CMake is that it can generate portable Makefiles or project files for various IDEs. It also allows writing platform checks for installed compilers, libraries, etc.

It’s also easy to switch between different build configurations with CMAKE_BUILD_TYPE, for example to use debug configuration you can run

cmake -DCMAKE_BUILD_TYPE=Debug .
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement