Adding Multiple Sources
As your project grows, it is common to split your code into multiple files to keep it organized and easier to maintain. In CMake, you add all the source files that belong to your program inside the add_executable command.
In this example, main.c contains the program entry point, while helper.c contains supporting functions. Both files are compiled and linked into a single executable by CMake.
main.c
helper.c
helper.h
CMakeLists.txt
1234567#include <stdio.h> #include "helper.h" int main() { print_message(); return 0; }
When working with multiple source files, functions shared between files must be declared in header files. In this example, the function print_message() is declared in helper.h and implemented in helper.c. Including the header file allows main.c to use the function correctly.
In CMakeLists.txt, you list every source file that should be compiled:
- CMake compiles each
.cor.cppfile separately. - The linker combines them into one executable.
- Header files are not compiled but tell the compiler how functions and data are defined.
CMake handles the build process automatically, but it is your responsibility to manage function declarations using header files.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Awesome!
Completion rate improved to 6.67
Adding Multiple Sources
Stryg for at vise menuen
As your project grows, it is common to split your code into multiple files to keep it organized and easier to maintain. In CMake, you add all the source files that belong to your program inside the add_executable command.
In this example, main.c contains the program entry point, while helper.c contains supporting functions. Both files are compiled and linked into a single executable by CMake.
main.c
helper.c
helper.h
CMakeLists.txt
1234567#include <stdio.h> #include "helper.h" int main() { print_message(); return 0; }
When working with multiple source files, functions shared between files must be declared in header files. In this example, the function print_message() is declared in helper.h and implemented in helper.c. Including the header file allows main.c to use the function correctly.
In CMakeLists.txt, you list every source file that should be compiled:
- CMake compiles each
.cor.cppfile separately. - The linker combines them into one executable.
- Header files are not compiled but tell the compiler how functions and data are defined.
CMake handles the build process automatically, but it is your responsibility to manage function declarations using header files.
Tak for dine kommentarer!