1. File Structure
mkdir buildcmake .. -G "Unix Makefiles"make
2. Code Explanation
# CMake recommends using "out-of-source builds" to avoid polluting the source code directory.
# Create a build directory (name can be arbitrary, e.g., build/)
mkdir build
# Enter that directory
cd build
# Specify the parent directory of CMakeLists.txt (i.e., the source code directory)
# If no generator is specified, CMake will choose the default generator based on the platform.
# On Linux/macOS, the default is to generate Unix Makefiles (i.e., Makefile).
# On Windows, it may default to generating Visual Studio projects (requires the corresponding toolchain to be installed).
# Force the generation of Makefile -G "Unix Makefiles",
# The following code cannot be copied and pasted, it needs to be entered manually, likely due to WeChat encoding issues
cmake .. -G "Unix Makefiles"
# If using the Unix Makefiles generator, ensure that the make tool is installed on the system.
# Linux: sudo apt install build-essential (Debian/Ubuntu).
# macOS: Install Xcode Command Line Tools: xcode-select --install.
# Compile based on the generated makefile
make
# Delete cache files in the build directory and regenerate:
rm -rf CMakeCache.txt CMakeFiles/cmake .. -G "Unix Makefiles"
Main.cpp Source Code
#include <iostream>
#include <limits> // Used to clear the input buffer
void wait_for_key() {
std::cout << "\nPress Enter to continue...";
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
std::cin.get(); // Wait for the user to press Enter
}
int main() {
std::cout << "Hello from my_app!" << std::endl;
wait_for_key(); // Call pause function
return 0;
}
3. Practical Results