Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practices for structuring a C program (for CMake build)

I have a C program that was handed down to me by a developer who left. I am trying to figure out exactly what he had goign on and get the software re-arranged into something more logical so I can build it easier. I am using CMake to build, whereas he was using Make.

There is one src/ folder that had several source files in it, and out of those, about 4 had main() methods. The files with the main() methods are in files that are named more as if they are utilities, or tools, or whatever. This kind of strikes me as odd, because he also had a lib folder, with some other things in it that were built and looked more like libraries. Should I split out those main methods into "driver" source files, and make the methods that are also defined in those files to be other libraries? If I do this, I know how to make CMake go look for a library and build and link it to the driver for execution.

If it is acceptable to build those "library" source files where they are, in the src folder, should I just set CMake up to build everything in that folder all at once, or should I create a directory structure for at least some logical separation?

Just as an idea, here is the current directory structure

project
.../src
......file1.c
......file2.c <-has a main() as well as other methods
......file3.c
......file4.c <- has a main() as well as other methods
......file5.c
.../lib
....../lib1
........./file1.c <-references top level include folder files
........./file2.c
....../lib2
........./file1.c <-refs top level and local include files
........./file2.c
........./file2.h
.../scripts
.../include
.
.
.

Any advice on best practices for restructuring this build or configuring it in CMake is appreciated.

like image 418
Derek Avatar asked Feb 14 '26 02:02

Derek


1 Answers

It's never too late for an answer, so I'd propose:

project
.../CMakeLists.txt
     include_directories(include/)
     add_subdirectory(lib/lib1)
     add_subdirectory(lib/lib2)
     add_subdirectory(src/)  

.../lib/lib1/CMakeLists.txt
              add_library(lib1 file1.c file2.c)

.../src/CMakeLists.txt
         add_executable(test1 test1.c test2.c)
         target_link_libraries(test1 lib1)

Why does it work: include_directories are derived in sub-directories, all targets (and thus libraries) from add_subdirectory are exported throughout the whole project.

like image 157
Patrick B. Avatar answered Feb 16 '26 20:02

Patrick B.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!