3

I created a file.h and a file.c how can I compile them on Ubuntu?

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
user541409
  • 39
  • 3

3 Answers3

3

You only need to compile your .c file(s), not your .h file(s).

To compile file.c on Ubuntu, you can use GCC:

gcc file.c -o my_program

...or Clang:

clang file.c -o my_program

It is possible to precompile your header files, but you only need precompiled headers in particular cases. More information here.


If file.h is not in the same folder as file.c, you can use GCC or Clang's -I option.

Example if file.h is in the include/ folder:

gcc -I include/ file.c -o my_program

In file.c you still have this instruction, with only the filename:

#include "file.h"
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
  • 3
    I recommend `gcc -Wall -Wextra -g file.c -o file` or `clang -Wall -Wextra -g file.c -o myprog`, perhaps with `-I include/` since you need warnings and debug info (and `gcc` or `clang` don't provide them by default) – Basile Starynkevitch Mar 17 '18 at 10:47
  • 1
    And using `-Werror` too ensures that you don't try running code while it still has the compiler warning you — it converts all warnings into errors. – Jonathan Leffler Mar 17 '18 at 16:21
3

You can also use a more generic approach by the usage of a makefile.

Here is a short example of such a file:

# Declaration of variables
CC = gcc
CC_FLAGS = -w -Werror -Wall

# File names
# "prgoram" will be the name of the output produced from the make process
EXEC = program 
#Incorporates all the files with .c extension
SOURCES = $(wildcard *.c)
OBJECTS = $(SOURCES:.c=.o)

# Main target
$(EXEC): $(OBJECTS)
    $(CC) $(OBJECTS) -o $(EXEC)

# To obtain object files
%.o: %.c
    $(CC) -c $(CC_FLAGS) $< -o $@

# To remove generated files
clean:
    rm -f $(EXEC) $(OBJECTS)

To use this utility just make sure that the file itself is within the directory containing your source files and its name is either "makefile" or "Makefile". To compile the code simply run the following command from your working directory:

   make program

This command will automatically link all the source files within your working directory into one executable file with the name of "program". To run the program itself just use the command:

  ./program

To clean your project and the created executable you can run the command:

  make clean

The makefile is very powerful when dealing with larger projects that contain a larger number of source files. Here you can check for more guidance on how to use makefiles. This is also a very detailed tutorial on the topic.

Iliya Iliev
  • 151
  • 4
1

Use following command to compile your program(For GCC Compiler):

gcc file.c -o file

No need to compile file.h file.

msc
  • 33,420
  • 29
  • 119
  • 214