Search code examples
cjsongccvisual-studio-codeheader

Compiling in terminal and in VS code with multiple .c files (and including header files correctly). Am I doing this correctly?


I'd like to have some clarifications about compiling and running programs in C. Until now I have mostly used single .c files so now I'm trying to run programs with multiple .c files. I'm on Windows with gcc (mingw). Let's say that inside the same program folder there are:

  • file.c (functions' definitions)
  • header.h (function's prototypes)
  • main.c

Inside both .c files I have included the header with #include "header.h" .

In the terminal I tried to compile some programs made of multiple .c files like stated above with something like:

gcc file.c main.c -o main

and it created the main.exe file and the program ran correctly but then I tried with another program with the same "structure" and I got error messages that indicated the header file couldn't be found. So I added the header path with the -I command at the end of the command line and again it worked fine. But I don't know why in this case I needed to specific the header path.

Inside VS code I modified the task.json file to compile all the .c files in my workspace (${workspaceFolder}\\*.c) and also added the header path (-I${workspaceFolder}) and it works fine. So the task.json looks like this: (there are some italian phrases and I'm using gcc installed inside CodeBlocks's folder btw).

{
    "version": "2.0.0",
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: gcc.exe compila il file attivo",
            "command": "D:\\CodeBlocks\\MinGW\\bin\\gcc.exe",
            "args": [
                "-g",
                "${workspaceFolder}\\*.c", 
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe",
                "-I${workspaceFolder}"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": "build",
            "detail": "compilatore: D:\\CodeBlocks\\MinGW\\bin\\gcc.exe"
        }
    ]
}

Basically I'd like to know if I am doing this correctly or if there are other/easier ways to do it.


Solution

  • Yes actually, if you have a lot of file, instead manually type them with gcc, you can do a Makefile. https://github.com/kayofeld/makefile-gen : this is a plugin to generate automatically your Makefile with all the rules and your files in your directory. But, if you want to learn how to do one by yourself, you can check this site: https://www.cs.swarthmore.edu/~newhall/unixhelp/howto_makefiles.html