How can I compile a header file and a C file together? - c

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

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"

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.

Use following command to compile your program(For GCC Compiler):
gcc file.c -o file
No need to compile file.h file.

Related

Unix: Project Management with Make

My instructions are:
The steps necessary to produce this program are:
Compile cpp2html.c to produce cpp2html.o. (Important: the source code in this project is C, not C++, and so must be compiled and linked with gcc, not g++.)
Run the command
flex cppscanner.l
to produce the file lex.yy.c from the language description in cppscanner.l.
Compile lex.yy.c to produce lex.yy.o. (This often produces a warning message about extra tokens. Ignore it.)
Link the .o files to produce an executable program named cpp2html
Write a makefile that will carry out these steps. Your makefile should result in only the minimum required amount of steps when any input file to this process is changed. (Note: you will probably not be able to base this makefile upon my self-updating makefile as in the earlier part of the assignment. Instead, you will probably find it necessary to write this one from scratch.
Here is my makefile:
cpp2html: cpp2html.o lex.yy.o
gcc -g -DDEBUG cpp2html.o lex.yy.o
mv a.out cpp2html
lex.yy.o: lex.yy.c
gcc -g -DDEBUG lex.yy.c
lex.yy.c:
flex cppscanner.l
cpp2html.o: cpp2html.c
gcc -g -DDEBUG cpp2html.c
What am I doing wrong here? I get an error message saying:
collect2: error: ld returned 1 exit status
make: *** [cpp2html.o] Error 1
Your makefile does not build 'cpp2html' when invoked:
gcc -g -DDEBUG cpp2html.c
This is due tonight, so any suggestions would be greatly appreciated.
It's complaining about the following:
cpp2html.o: cpp2html.c
gcc -g -DDEBUG cpp2html.c
This line is trying to compile cpp2html.c to a.out.
Change that to
cpp2html.o: cpp2html.c
gcc -g -DDEBUG -c cpp2html.c
Do the same thing for the line that compiles lex.yy.c to lex.yy.o. The -c option tells gcc to only generate the object file and write it to the .o file.
You can take advantage of other options and some built-in variables. Here's a suggestion:
cpp2html: cpp2html.o lex.yy.o
gcc -g -DDEBUG -o $# $?
$# evaluates to the name of the target. $? evaluates to the list of dependencies (the .o files). The -o option tells gcc to write the resulting binary to the specified file name instead of a.out.
You can also take advantage of implicit rules:
%.o : %.c
gcc -g -DDEBUG -c $<
This will build any .c file to the corresponding .o file, so you don't need to repeat the same commands for cpp2html.c and lex.yy.c.
Edit
FWIW, here's how I'd structure the makefile (with annotations; assumes Gnu make):
# Variables used by implicit rules
CFLAGS=-g -DDEBUG -Wall -Werror # flags for gcc
LFLAGS= # flags for flex, currently none
LEX=flex # lexer
CC=gcc # C compiler
# Variables to make life easier
LSRCS=cppscanner.l # All of our flex source files
SRCS=cpp2html.c $(patsubst %.l,%.c,${LSRCS}) # All of our C source files
OBJS=$(patsubst %.c,%.o,${SRCS}) # All of our object files
TARGET=cpp2html # Final target name
${TARGET} : ${OBJS}
${CC} ${CFLAGS} -o $# $^ # Explicit rule to build target
# $# expands to target name
# $^ expands to list of all prerequisites
clean:
rm -rf *.o $(patsubst %.l,%.c,${LSRCS})
That's it. We're relying on implicit rules to build the .l file to a .c file, and to build the .c files to .o files. The implicit rules use the LEX, CC, LFLAGS and CFLAGS variables to run the right commands with the right options. We only need the single explicit rule to build our final executable.
The advantage of structuring a makefile like this is that you can add files to the project without having to add new rules.
I think all of the above is correct; my main box is shut down at the moment so I can't test it. Refer to the Gnu Make manual for more details.

Generate output files in separate directory in c using make file

How can i build a c project using makefile that generate intermediate and output files in separate directory other than source?
Current form of my makefile is
CC = g++
LDLIBS = -lm
all: test_makefile
test_makefile: file1.o file2.o file3.o file4.o test_makefile.o
clean:
rm test_makefile *.o
I want to generate these intermediate files in /build directory.
Can anyone help me to modify this make file?
You might want to consider using Automake (https://www.gnu.org/software/automake/) for projects of significant size with separate source and build directories.
Without automake, and considering that by default compilers generate output files in CWD, you can simply create your makefile in the build directory. Here's an example that uses ../ as source directory:
all: foo
foo: ../x.cc
$(CXX) $< -o $#

Why is my makefile recompiling even if I just compiled the source?

I have a simple makefile that compiles a p.c file to an executable using gcc on Linux.
The p.c file depends on a a.h file.
My makefile looks like this:
//makefile
CC = gcc
build: p.c a.h
$(CC) -o out p.c
clean:
rm -f *.exe
rebuild: clean build
Your makefile doesn't produce the files it promises to produce, namely build, clean and rebuild. Since these targets are not files they should be marked as phony targets:
.PHONY: build clean rebuild
build target should be:
build : out
out : p.c a.h
$(CC) -o $# p.c
This part
build: p.c a.h
$(CC) -o out p.c
says "I'm compiling with $(CC) -o out p.c and the result will be a file named 'build'". Since you lied to make (this creates the out file instead), it will try building 'build' again.
There's a lesson for Makefile writers here: always use the $# variable (denoting the target) to avoid this error:
out: p.c a.h
$(CC) -o $# p.c
For more advice, see Paul's Rules for Makefiles.
Learner, here is an example of using a variable to store the name of the executable. This way you only need to specify it in one place at the start of your Makefile:
EXECUTABLE = out
.PHONY: build clean rebuild
build: $(EXECUTABLE)
$(EXECUTABLE): p.c a.h
$(CC) -o $# p.c
clean:
rm -f $(EXECUTABLE)
rebuild: clean build
Normally you would also have your .c and .h files listed in variables too so that you can add/remove files from your build easily without having to search through your Makefile for all of the places that they are used.
Makefiles have the general syntax:
target : dependencies
commands to make target from dependencies
So your Makefile expects to make a file called build using the build : p.c a.h target.
Since the commands don't actually make this file each time you call make it's having to redo the command.
(PS: Linux binaries don't have a .exe extension)
If you want to avoid always recompiling the source, then your target should depend on the object file, not the source file:
target.exe : p.o
$(CC) -o $# $?;
p.o: p.c a.h
$(CC) -c $# $?;
A typical makefile doesn't usually have an explicit rule per object file, nor does it usually list explicit dependencies between implementation and header files; you usually see an implicit rule like
%.o : %.c
$(CC) -c $(CFLAGS) $?;
(where $? indicates the list of prerequisites for that target) or, if your project is dead simple (one source file), you don't even need that; you can usually get away with
all: target
target: target.o
assuming you have a file named target.c, the above will build target using the default compiler and CFLAGS options.
Likewise, a typical makefile (at least in my experience) doesn't explicitly list header dependencies; rather, it relies on a compiler option to generate those dependency lists automagically (for gcc, that option is -M). See here for an example.
I have understood that it is necessary for the 'target' and 'output file' names to match fully for the make to be able to recognize if recompilation is not required. So in case of Windows environment (as make I have tried mingw32-make.exe) it should be like this:
build.exe: p.c a.h
gcc -o build.exe p.c
or
build.exe: p.c a.h
gcc -o build p.c # .exe is added automatically to generated file
This code will lead to recompilation always when make is called:
build: p.c a.h
gcc -o build p.c # target is "build" and it is not the same as "build.exe" which is the output of compilation

What is wrong with this Makefile? (header files not found)

I am modifying an old makefile in order to build a C extension for postgreSQL. The Makefile currently looks like this:
PGLIB = /usr/lib/postgresql/8.4/lib
PQINC = /usr/include/postgresql/8.4/server
CC=gcc
override CFLAGS+= $(CFLAGS_SL) -DPG_AGGREGATE
SHLIB = pg_myextlib
SRC = foo.c \
foobar.c
OBJS = foo.o \
foobar.o
all: $(OBJS)
$(CC) -shared -o $(SHLIB)$(DLSUFFIX) $(OBJS) -I$(PQINC)
cp *.so $(PGLIB)
clean:
rm -f $(SHLIB) $(OBJS)
The error I get when I run make is:
common.h:58:22: error: postgres.h: No such file or directory
Which suggests that the include path is not being added (the file exists in $PQINC).
Its a long time since I wrote the Makefile - and I haven't written many since. As an aside, I am pretty sure that 'shared' is not the gcc flag to build shared libs on Ubuntu (my current dev box) - I think the flag should be 'fPIC' - can someone confirm this?
I am runing gcc v4.4.3 on Ubuntu 10.0.4 and compiling for use with PG 8.4
Try moving the -I$(PQINC) from target all to the end of line that starts with override CFLAGS.
Placing -Isomething on the compiler line which turns object files, like those in $(OBJS), into executable will have no effect whatsoever.
You need to do it when you compile the source files.
Since your makefile doesn't explicitly show the rule for processing source files, it may well be using a default one, which is incredibly unlikely to know about PQINC.
You seem to be using the default rules to build foo.o from foo.c, which doesn't have your -I. Try adding the following rule to your Makefile:
.c.o:
$(CC) $(CFLAGS) -c $< -o $# -I$(PQINC)

Determining C executable name

When we are compiling a C program the output is stored in a.out. How can we redirect the compiled output to another file?
Most C compilers provide an option for this, such as the -o option for gcc and some others:
gcc -o gentext gentext.c
cc -o mainprog -Llib -lmymath firstbit.c secondbit.o
xlc -o coredump coredump.c
-ofilename will make filename instead of a.out.
According to the manual:
-o <file> Place the output into <file>
In Unix, where C originated from, C programs are usually compiled module-by-module, and then the compiled modules are linked into an executable. For a project that consists of modules foo.c and bar.c, the commands would be like this:
cc -c foo.c
cc -c bar.c
cc -o myprog foo.o bar.o
(With -c, the output filename becomes the source file with the suffix replaced with .o.)
This allows you to also re-compile only those modules that have changed, which can be a big time saver for big programs, but can also become pretty tricky. (This part is usually automated using make.)
For a single-module program there's not really any point in first compiling to a .o file, and then linking, so a single command suffices:
cc -o foo foo.c
For single-module programs, it is customary to call the resulting executable program the same as the C source file without the .c suffix. For multi-module programs, there is no hard custom on whether the output is named after the file with the main function or not, so you're free to invent whatever strikes your fancy.
With the -o option.
gcc main.c -o myCoolExecutable.o
This is ok if your program consists of a single file. If you have more files I suggest using make: create a Makefile and then run the command make.
A Makefile is a file containing some rules for compilation.
An example can be the following (# means the line is a comment):
CXX = gcc
#CXXFLAGS = -std=c++11
#INC_PATH = ...
#LIBS = ...
SOURCEDIR := yourSourceFolder
SOURCES := $(wildcard $(SOURCEDIR)/*.c)
OBJDIR=$(SOURCEDIR)/obj
OBJECTS := $(patsubst $(SOURCEDIR)/%.c,$(OBJDIR)/%.o, $(SOURCES))
DEPENDS := $(patsubst $(SOURCEDIR)/%.c,$(OBJDIR)/%.d, $(SOURCES))
# ADD MORE WARNINGS!
WARNING := -Wall -Wextra
# .PHONY means these rules get executed even if
# files of those names exist.
.PHONY: all clean
# The first rule is the default, ie. "make",
# "make all" and "make parking" mean the same
all: yourExecutableName
clean:
$(RM) $(OBJECTS) $(DEPENDS) yourExecutableName
# Linking the executable from the object files
# $^ # "src.c src.h" (all prerequisites)
yourExecutableName: $(OBJECTS)
$(CXX) $(WARNING) $^ -o $#
#$(CXX) $(WARNING) $(CXXFLAGS) $(INC_PATH) $^ -o $# $(LIBS)
-include $(DEPENDS)
$(OBJDIR):
mkdir -p $(OBJDIR)
$(OBJDIR)/%.o: $(SOURCEDIR)/%.c Makefile | $(OBJDIR)
$(CXX) $(WARNING) -MMD -MP -c $< -o $#
Shortly CXX variable defines your compiler (gcc, g++), with CXXFLAGS you can define flags for your compilation (i.e. -std=c++11). Then you can include and define custom (INC_PATH and LIBS: not set in the example). With SOURCEDIR you can specify your source code directory (where *.c files are).Then SOURCES is basically telling that the source files for the compilation are all the files having extension *.c.
The Makefile contains a set of rules whose structure is the following:
output: inputs
commandToExecute
The rule to generate your executable file is
yourExecutableName: $(OBJECTS)
$(CXX) $(WARNING) $^ -o $#
which is equivalent to gcc -Wall -Wextra $(OBJECTS) -o yourExecutableName.
$(OBJECTS) are the object file resulting from the compilation. When the above rule is executed, if they are not found make will continue scanning the file to find a rule to generate them. In this case the rule to generate these files is:
$(OBJDIR)/%.o: $(SOURCEDIR)/%.c Makefile | $(OBJDIR)
$(CXX) $(WARNING) -MMD -MP -c $< -o $#
If further information is needed let me know.
If foo will be your executable and bar.c is your source file then the command is:
gcc -o foo bar.c
Compile using:
cc -o <opfilename> <filename.c>
Execute using:
./<opfilename>
gcc filename.c -o outputfile
This command will directly create an outputfile.exe OR outputfile.out according to operating system. In place of filename.c OR outputfile we can enter path, as shown below.
gcc ./home/user/filename.c -o ./home/outputfile
The format of giving the Name of .exe file according to the User Choice in C Language
step 1 :- Run the gcc (or the compiler you have) in the below format on the Terminal
gcc -o put_your_name_you_want_to_give (space) your_file_name_you_want_to_execute
NB:- If you are Running "Vs Code" Use the 'Tab' key for the Auto completion.
step 2 :- Write down the name of the program in format
.\the_name_you_have_given.exe
you are done!
Assuming you are in ubuntu
step-1: run gcc with these commands to compile filename.c
gcc filename.c -o filename.out
filename.out will be created, (it might or might not be shown where the other files are stored)
step-2: execute the filename.out by
./filename.out
step-3: wait for the output
thats it , you are done

Resources