Writing a makefile for a C++ program

2019-06-12 22:12发布

问题:

Can someone help me write my first makefile?

I have a helloworld.cpp code in /path/to/main/code/helloworld.cpp. And then I have just included a .h file #include "SFML/network.hpp".

Now SFML library is saved in /path/to/SFML/Library

It would be great if someone can help me getting started in this. In the mean time, I am trying to read thru the literature but its very overwhelming.

回答1:

Although you may need to learn the traditional GNU Makefile syntax in order to work with other projects, I recommend using CMake for your own projects because it is simpler and more intuitive.

A CMake file for your example would go in a file called CMakeLists.txt in the root directory of your project (same as the source in this case) and look like this:

project(HelloWorld)                        # Name your project.
add_executable(helloworld helloworld.cpp)  # Specify an executable to build.
link_directories(/path/to/SFML)            # Tell it where your libraries are.
target_link_libraries(helloworld Library)  # Tell it which library to link.

If you want to be able to #include headers from SFML without including the directory name every time, then you can also write:

include_directories(SFML)                  # Tell it where your headers are.

Further documentation on writing CMake files and running CMake is available on the website.

Lastly, CMake often gives a noisy but harmless message requesting that you put a line like this at the top of your CMakeLists.txt file:

cmake_minimum_required(VERSION 2.8)        # Quell warnings.

Cheers.



回答2:

It is probably simple on its own, but just wanted to recommend genmake.pl, I used this to great effect for my school project. It is quite easy to use, it generates a skeleton Makefile for you and you need to fill in things like the path to SFML.



回答3:

If you're using ACE (Adaptive Communication Environment), it comes with a very powerful makefile creation utility called MPC (Makefile Project Creator)

To compile a simple program, and auto-generate GNU makefiles, a minimal example could be:

project(*my_project) : baseWorkspace {
       exename = my_project
       exeout = ./
       Source_Files {
          main.cpp
       }
   }

I've found that the beauty of using this tool is that it can inherit "base" workspaces, almost like polymorphism in C++. The libraries defined in the "base" are used in the current project, allowing the programmer to utilize various building blocks to easily manipulate and create projects rapidly.

I'm confident only the MPC portion of ACE can be downloaded and used via an RPM, I'll search around and see if I can find an appropriate example for you.