Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C Project Structure

C Project Structure

C project structure refers to the way directories are laid out to organize the source code, header files, build scripts, and resource files of a C language project.

A clear and standardized project structure makes large C projects easy to maintain, facilitates collaboration among multiple people, and simplifies the build and deployment process.


Why a standardized project structure is needed

When beginners write C code, they often pile all files in one directory, which causes serious problems as the project grows.

Duplicate header files, naming conflicts, slow compilation, and difficulty locating code - these kinds of chaos will eventually make the project hard to maintain.

A conventional directory structure helps you and your team members quickly understand the overall project, and also allows automated build tools such as Make and CMake to work efficiently.


Standard directory structure

The following is a recommended directory structure for a typical C project, suitable for small and medium-sized projects.

Each directory has clear responsibilities and a clear hierarchy:


Core directories in detail

The following explains the responsibilities and best practices of each directory one by one.

src/ - source code directory

Stores all .c source files, split into multiple files by module.

One .c file per module, with file names corresponding to their functions, for quick location.

The entry function main() is usually placed in main.c; do not mix in business logic.

Example

/* File path: src/main.c */

#include "utils.h" /* custom utility function header file */

#include "database.h" /* database operation header file */

#include      /* Standard input and output */

int

main

(

int

argc

,

char

argv

[

]

)

{

   

/* argc: number of command-line arguments, argv: argument array */

   

printf

(

"RUNOOB C project started\n"

)

;

    init_database

(

)

;

   

/* Initialize the database connection */

    print_version

(

)

;

   

/* Output version information (from the utils module) */

   

return

0

;

           

/* Returning 0 indicates the program exited normally */

}

include/ - header file directory

Stores all .h header files, which are the interface definitions for communication between modules.

Header files contain only declarations (function prototypes, structures, macros, enums), not implementation code.

Example

/* File path: include/utils.h */

#ifndef UTILS_H /* include guard macro to prevent duplicate inclusion */

#define UTILS_H

/* Project name and version number (macro constants, named in all uppercase) */

#define PROJECT_NAME  "RUNOOB"

#define VERSION_MAJOR 1

#define VERSION_MINOR 0

/* Structure: represents a two-dimensional coordinate point */

typedef

struct

{

   

int

x

;

             

/* X coordinate */

   

int

y

;

             

/* Y coordinate */

}

Point

;

/* Function declaration: calculate the distance between two points */

double

distance

(

Point a

,

Point b

)

;

/* Function declaration: output version information */

void

print_version

(

void

)

;

#endif /* UTILS_H */

tests/ - test directory

Stores unit test code; usually one test file corresponds to one source module.

It is recommended to use testing frameworks such as CUnit and Check, or you can write simple assertion tests by hand.

build/ - build directory

Stores intermediate files (.o) generated by compilation and the final executable file.

This directory is automatically generated and cleaned by the build system and is not included in version control (it should be written into .gitignore).

lib/ - third-party library directory

Stores third-party static libraries (.a) or dynamic libraries (.so / .dylib) that the project depends on.

It is more recommended to use package managers (such as vcpkg, Conan) to manage dependencies rather than manually copying library files.

doc/ - documentation directory

Stores project design documents, API descriptions, changelogs, and so on.

It is recommended to use Doxygen to automatically generate API documentation from source code comments.


Header file management

Header files are a key bridge for collaboration between modules in a C project; poor management can cause numerous compilation problems.

The following figure shows the reference relationships between header files in a typical C project:

Each .c file corresponds to a .h file with the same name, and the .h file serves as the public interface of the module.

Include guards must be used in header files to prevent duplicate inclusion.

Do not define global variables in header files. If multiple .c files include the same header file, repeated definitions of global variables will cause link errors. The correct approach is to declare them with extern in the header file and define them in one .c file.


Build system

The build system is responsible for compiling source code into executable files, managing compilation order, dependencies, and compilation options.

Makefile - a classic build tool

Makefile controls the compilation process by defining rules (targets, dependencies, commands).

Suitable for small and medium-sized projects, and pre-installed on almost all Unix/Linux systems.

Example

File path: Makefile

Makefile basic structure: target: dependencies\n\tcommands

Compiler settings

CC      =

gcc

                   

Specify the C compiler

CFLAGS  =

-Wall

-Wextra

-g

     

Compilation options: all warnings + debugging information

INCLUDE = -I.

/

include          

Header search paths

TARGET  = runoob_app            

The name of the final generated executable file

Source files and object files

SRCS    = $

(

wildcard src

/*

.c

)

 

Automatically collect all .c files under src/

OBJS    = $

(

SRCS:.c=.o

)

       

Derive the corresponding .o file names

Default target: generate the executable file

$

(

TARGET

)

: $

(

OBJS

)

        $

(

CC

)

$

(

CFLAGS

)

-o

$

@

$^

       

@

echo

"Build successful: ./$(TARGET)"

Compilation rule: .c -> .o

%

.o:

%

.c

        $

(

CC

)

$

(

CFLAGS

)

$

(

INCLUDE

)

-c

$

<

-o

$

@

.PHONY: clean

clean:

       

rm

-f

$

(

OBJS

)

$

(

TARGET

)

       

@

echo

"Build files cleaned"

CMake - a cross-platform build system

CMake describes the project structure through CMakeLists.txt and automatically generates build files for each platform.

Suitable for medium and large projects that need cross-platform support.

Example

File path: CMakeLists.txt

The minimum required version of CMake

cmake_minimum_required

(

VERSION

3.10

)

Project name and language

project

(

runoob_app C

)

Set the C standard to C11

set

(

CMAKE_C_STANDARD 11

)

set

(

CMAKE_C_STANDARD_REQUIRED

ON

)

Collect all source files

file

(

GLOB SOURCES

"src/*.c"

)

Define header file search paths

include_directories

(

include

)

Generate the executable file

add_executable

(

${PROJECT_NAME}

${SOURCES}

)

Optional: link third-party libraries

target_link_libraries(${PROJECT_NAME} PRIVATE m)

CMake build steps:



$ mkdir build && cd build

$ cmake ..

$ make

$ ./runoob_app

RUNOOB C 项目启动

版本: v1.0


Compilation Workflow

Understanding the entire process of C source code from writing to running helps troubleshoot compilation and linking errors.

The following figure shows the four stages from a .c file to an executable file:

Preprocessing Preprocessing Expand #include and #define Compilation Compilation C -> assembly code Assembly Assembly Assembly -> .o object files link Linking .o + libraries -> executable file -> .i file -> .s file -> .o file -> executable file gcc -E → -S → -c → (ld)

Step-by-step compilation commands

Using GCC, you can execute step by step and observe the output of each stage:



# 1. Preprocessing: Expand all macros and headers

$ gcc -E src/main.c -I./include -o main.i



# 2. Compile: Convert preprocessed results to assembly code

$ gcc -S main.i -o main.s



# 3. Assemble: Convert assembly code to object file

$ gcc -c main.s -o main.o



# 4. Link: Link all target files as executable programs

$ gcc main.o utils.o -o runoob_app


Common examples

The following is a complete small C project example covering the whole process from directory creation to compilation and running.

Create the project skeleton



$ mkdir -p runoob_project/{src,include,tests,build,lib,doc}

$ tree runoob_project/

runoob_project/

├── build/

├── doc/

├── include/

├── lib/

├── src/

└── tests/

Write module code

Example: math utility module

/* File path: src/math_utils.c */

#include "math_utils.h" /* its own header file */

#include          /* Standard math library, provides sqrt() */

/* Calculate the Euclidean distance between two points */

double

distance

(

Point a

,

Point b

)

{

   

int

dx

=

a.

x

b.

x

;

         

/* Difference in the x direction */

   

int

dy

=

a.

y

b.

y

;

         

/* Difference in the y direction */

   

return

sqrt

(

dx

dx

dy

dy

)

;

 

/* Pythagorean theorem */

}

/* Determine whether a number is prime */

int

is_prime

(

int

n

)

{

   

if

(

n

<

2

)

return

0

;

       

/* Numbers less than 2 are not prime */

   

for

(

int

i

=

2

;

i

i

<=

n

;

i

++

)

{

       

if

(

n

%

i

==

0

)

return

0

;

/* A factor was found, so it is not prime */

   

}

   

return

1

;

                   

/* No factor was found, so it is prime */

}

Example: the corresponding header file

/* File path: include/math_utils.h */

#ifndef MATH_UTILS_H

#define MATH_UTILS_H

/* Two-dimensional point structure */

typedef

struct

{

   

int

x

;

   

int

y

;

}

Point

;

/* Calculate the distance between two points */

double

distance

(

Point a

,

Point b

)

;

/* Determine whether n is prime, return 1 for yes, 0 for no */

int

is_prime

(

int

n

)

;

#endif /* MATH_UTILS_H */

Compilation and running



$ cd runoob_project

$ mkdir build && cd build

$ cmake ..

-- Configuring done

-- Generating done

$ make

[100%] Built target runoob_app

$ ./runoob_app

RUNOOB 项目运行成功!

Point(0,0) 到 Point(3,4) 的距离 = 5.00

7 是质数: 是


Notes

Include guard macros must be unique. It is recommended to use the project_name_module_name_H naming convention to avoid macro name conflicts between different projects.

Do not use #include "file.c" to reference source files. This causes the same function to be compiled multiple times, leading to duplicate definition errors. Always list all .c files in the compilation command, or use Makefile/CMake for management.

Summary of the responsibilities of each directory:

directory Responsibility Whether included in version control
src/ .c source file Is
include/ .h header file, public interface Is
tests/ Test code Is
build/ Compilation intermediates, executable files No (add to .gitignore)
lib/ Third-party library files Depends on the situation
doc/ Project documentation Is

A complete .gitignore example:



# Build artifacts

build/

*.o

*.out

*.exe



# IDE 配置

.vscode/

.idea/



# macOS

.DS_Store


Common questions

Q: Why does the compiler report undefined reference during compilation?

This is an error in the linking stage, indicating that the function was declared but no implementation was found.

Check whether the corresponding .c file has been added to the compile command, or whether the library file is linked correctly.

Q: Should a header file use <> or ""?

Standard library headers use , and the compiler searches in the system path.

Custom headers use "utils.h"; the compiler first searches the current directory, then the system path.

Q: What is the difference between static and dynamic libraries?

A static library (.a) is copied into the executable at link time; the program is self-contained but larger.

A dynamic library (.so / .dylib) is loaded at runtime and can be shared by multiple programs; you need to ensure the target system has the corresponding version.