C - Makefile compiles after header file changes, but changes dont take effect - c

I have 3 files in this program, lab4.c, functions.h, functions.c
The lab4.c calls a function multiply(), whose prototype is in functions.h and is defined in functions.c. Multiply then used multiple other functions from functions.c. The only includes I have for this is in lab4.c including functions.h, do I need more? The problem I am having is described below
lab4:
#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
int main(void) {
...
}
functions.h:
#ifndef FUNCTIONS
#define FUNCTIONS
void divideByPowerOf2(unsigned int* a, int power);
void multiplyByPowerOf2(unsigned int* a, int power);
...
#endif /* FUNCTIONS */
functions.c:
void divideByPowerOf2(unsigned int* a, int power){
*a >>= power;
}
void multiplyByPowerOf2(unsigned int* a, int power){
*a <<= power;
}
...
Currently, my makefile looks like this:
Makefile:
#Makefile
all: lab4
lab4: lab4.o functions.o functions.h
gcc -Wall -o lab4 lab4.o functions.o
lab4.0: lab4.c
gcc -c lab4.c
functions.o: functions.c
gcc -c functions.c
now this will recompile when I change the header file, but the changes dont actually take effect. For example, if I change the header file to
#ifndef FUNCTIONS
#define FUNCTIONS
void divideByPowerOf2(unsigned int* a, int power);
//void multiplyByPowerOf2(unsigned int* a, int power);
...
#endif /* FUNCTIONS */
the program still works just fine. Im assuming I may have messed up linking the files with includes and everything, as that usually confuses me. For example, does functions.c need to refer to anything? and does functions.h need any kind of reference to the .c files? How do I get this to work properly so that if I change the header file, it recompiles and actually uses the new header
Thanks for any help!

First, there's a typo here:
lab4.0: lab4.c
should be
lab4.o: lab4.c
then, your function.h should be on the source => object dependency lines, not on the object => executable line, else, if you change the .h file, it just re-links without rebuilding the .o files: it changes nothing.
Moreover, it's good to use -Wall, but you have to use it when you compile your files, not when you link the executable, or you'll miss the actual compilation warnings (-Wall during the link phase only is pretty useless).
For instance, the -Wall flag would show you that commenting a prototype generates an "implicit declaration" warning (which can lead to an improper call/return values of a function). It's even more effective with -Werror, which turns warnings into errors, so you cannot ignore warnings.
Here's how your makefile should look like:
all: lab4
CFLAGS = -Wall
lab4: lab4.o functions.o
gcc -o lab4 lab4.o functions.o
lab4.o: lab4.c functions.h
gcc $(CFLAGS) -c lab4.c
functions.o: functions.c functions.h
gcc $(CFLAGS) -c functions.c
note that if you only have 2 source files and they're small enough, you could even not use the make file by just running:
gcc -Wall -o lab4 lab4.c functions.c
in a script. That's not adapted if you have too many / big source files, because it rebuilds everything everytime.

Related

Compiling header files in ubuntu. What do I type in terminal?

I'm pretty sure this is a simple question but I've searched online for about half an hour.
I have 3 files:
02_01.c
#include <stdio.h> // Notice the library included in the header of this file
#include <stdlib.h>
#include "myLibrary.h" // Notice that myLibrary.h uses different include syntax
#define MAX_LENGTH 21.8
#define WORK_WEEK 5
int main(void) {
function1();
return EXIT_SUCCESS;
}
myLibrary.c
void function1(void){
puts("It works :)");
}
void function2(void){
//This function does nothing as well
}
myLibrary.h
#ifndef MYLIBRARY_H_
#define MYLIBRARY_H_
void function1(void);
void function2(void);
#endif /* MYLIBRARY_H_ */
First, I navigate to my working directory.
Normally in a file with no local headers I would type:
gcc -o 02_01 02_01.c
./02_01
and it would work.
I've tried a variety of things like:
gcc -o 02_01 02_01.c myLibrary.c
which gives me an error "implicit declaration of function 'puts'
gcc -o myLibrary myLibrary.c which also gives the same error.
What should I be typing in the terminal in ubuntu?
So I'm assuming that the puts() function in myLibrary.c is not connected to 02_01.c which is where I include stdio.h.
You must include required headers in every file, where you using included functions. In your case, you must include #include <stdio.h> in beginning of your myLibrary.c file.
Also, you probably want to build .a library and link with it later.
So, finally:
Compile lib:
gcc -c -o mylib myLibrary.c
Make static lib:
ar rcs libMyLib.a mylib
Compile app and link together:
gcc -o 02_01 02_01.c -L. -lMyLib

call c function from a .c file with a main function

I have two .c files that both have mains. One of the files has a function that I would like to use in the other main. Is it possible to reference this other function without copying and pasting it into the other .c file?
No you don't need to copy and paste, suppose you have this
program-one.c
First program.
#include "common.h" /* This should be implemented */
int main(void)
{
do_program_one_stuff();
common_function();
return 0;
}
program-two.c
Second program.
#include "common.h" /* This should be implemented */
int main(void)
{
do_program_two_stuff();
common_function();
return 0;
}
You need a third .c file and a .h file, like this
common.c
Common Functions Implementation.
void common_function()
{
/* Do it here */
}
common.h
Common Functions Header.
void common_function();
You now can compile a single binary for each program consisting of two files, the program specific .c file and common.c.
The right way to do it is to have a Makefile and generate object code first, and then link the object files togeather, thus compiling each file only once.
Makefile
This is a GNU make Makefile using gcc as the compiler.
CC = gcc
CFLAGS = -Wall -Wextra -Werror -g3 -O0 # enable debug symbols and warnings
LDFLAGS = # linker flags here ...
OBJ = common.o program-one.o program-two.o
all:
$(CC) $(LDFLAGS) common.o program-one.o -o program-one
$(CC) $(LDFLAGS) common.o program-two.o -o program-two
%.o: %.c
$(CC) $(CFLAGS) -c $<
clean:
#rm -fv *.o program-one program-two
EDIT: in response to your comment I would suggest the following
#define main ignore /* Or whatever name you want */
#include "the-student-implementation.c"
#undef main
int main(void)
{
/* This would be your `main()' */
return 0;
}
The best solution is what iharob suggested, but if for some reason that isn't possible, you could surround the main() in the file containing the common function with #ifdef USE_MAIN, then only define the USE_MAIN identifier in the command to build that project. When you build the other project that doesn't have USE_MAIN defined, the preprocessor will cause the second main() to be skipped, so the compiler won't be confused.
But unless this is really needed, I highly recommend splitting this into three files: main1.c, main2.c, and common.c/common.h

C language prototype creation

I have this block of code. I have to move the given function display_name() into another .c file, compile it, and find the error that was caused due to the migration of the function and correct it by creating a header file with a prototype. How can I do it?
#include <stdio.h>
#include <string.h>
#include <ctype.h>
char student[]="Rasmus Lerdorf";
void display_name()
{
printf("Student Name : %s",student);
}
int main()
{
display_name();
}
these are the changes i made but again i still get an error in the main.cpp. it doesnt allow me to include the displayname.h file.
displayname.h
void display_name(void);
displayname.cpp
#include <stdio.h>
#include "displayname.h"
char student[] = "Rasmus Lerdorf";
void display_name()
{
printf("Student Name : %s", student);
}
main.cpp
#include <stdio.h>
#include "displayname.h"
int main()
{
display_name();
}
errors are:
3 IntelliSense: identifier "display_name" is undefined c:\Users\konstantinos\Desktop\main\main.cpp 7 2 Cproject
2 IntelliSense: cannot open source file "displayname.h" c:\Users\konstantinos\Desktop\main\main.cpp 2 1 Cproject
Error 1 error C1083: Cannot open include file: 'displayname.h': No such file or directory c:\users\konstantinos\desktop\main\main.cpp 2 1 Cproject
Prototype functions work like this: for each set of functions that you write (except main) you need a definition and an implementation. Definitions are usually stored in header files (extension .h) whereas implementations are stored in source files (extension .c).
Here is an example of how you could arrange your code to solve your problem.
Definition: display.h
// This file contains the definitions of the functions which you want to call from another file
void display_name(void);
Implementation: display.c
#include "display.h"
#include <stdio.h>
static char student[]="Rasmus Lerdorf";
void display_name()
{ printf("Student Name : %s",student);
}
With both the definition defined and the desired implemented, now you can call the function from your main source file.
Implementation: main.c
#include "display.h"
#include <stdio.h>
int main()
{
display_name();
}
This is how you link together a prototype of a function and the implementation of a function. You can expand this by adding more prototypes to display.h, implementing those prototyped functions in display.c, and then calling them throughout your code.
To build, both of these .c files must be included in your build phase. If you build from the command line, you need to do something like this (I'm assuming that your compiler is gcc):
cc display.c main.c -o program
Hope this helps.
Your header file, let's call it displayname.h should contain the declaration:
void display_name(void);
It's usually also best to create an include guard, which avoids causing problems if a header is included more than once:
#ifndef DISPLAYNAME_H
#define DISPLAYNAME_H
void display_name(void);
#endif /* DISPLAYNAME_H */
Then, in your displayname.c, you would include that header plus any others needed by the function, and define your constant and the function:
#include <stdio.h>
#include "displayname.h"
char student[]="Rasmus Lerdorf";
void display_name()
{
printf("Student Name : %s",student);
}
And in your main.c, you would also include that header:
#include "displayname.h"
int main()
{
display_name();
return 0;
}
I don't know what compiler you are using, but if you're on a Unix-like system (Linux, Mac OS X, or something like msys or Cygwin under Windows), you would compile and link them as follows (you can replace cc with your specific compiler, such as gcc or clang, though on most systems cc should exist and point to the default compiler for that system):
cc -c -o displayname.o displayname.c
cc -c -o main.o main.c
cc -o myprogram main.o displayname.o
You could also abbreviate this as:
cc -o myprogram main.c displayname.c
I also recommend, when you are learning, to use the -Wall -Wextra -Werror flags, to give you as many warnings as possible, and not allow compilation to proceed if there are any warnings. To make this more convenient, so you don't have to type the whole command every time, you can define a simple Makefile; the following uses GNU make syntax, if you don't have GNU make let me know and I'll edit it to use a more portable syntax:
CFLAGS=-Wall -Wextra -Werror
myprogram: main.o displayname.o
cc -o $# $^
%.o: %.c
cc -c $(CFLAGS) -o $# $<
main.o: displayname.h
displayname.o: displayname.h
If you have this set up, you can just type make and it will recompile everything that it needs to.
edit: I see now from your comments that you are using Visual Studio, so the above tips on how to compile and link using cc and make are not relevant to you. It has been too long since I have used Visual Studio to walk you through that myself, but Microsoft has a reasonable walkthrough of how to create and build a project that you can follow. The tutorial is for C++, but it should work similarly for C, just keep in mind that files should be named .c if they are written in C, and only .cpp if they are written in C++.
i did what you said! i created the 3 specific files displayname.h for the prototype , displayname.cpp in which the function display_name() stays and main.cpp in which i call the function display_name(). the problem again is that when i include the file displayname.h in the displayname.cpp it works fine, but when i include it in the main.cpp i have an underline error in the include. what is wrong?

Compiling multiple files in C

I recently asked this question about compiling multiple files in C so that a file main.c can reference a file modules.c. The answer ended up being to make the modules file into a header file and having main import it.
I have now been told that this is an incorrect way to do it, as C supports modular compilation. My Makefile is below, and this is supposedly supposed to be correct, but I receive errors for each function call in main.c -- warning: implicit declaration of function X.
What do I need to do to compile this correctly, with two .c files rather than a .c and .h file? The main.c file has a main() function that needs to be able to call the functions in modules.c.
Makefile:
#################################################################
# Variables
# -- allows C-source and assembly-source files mix. Again, the
# -- indented lines start with a TAB(^I) and not spaces..
#################################################################
CFLAGS = -g -Wall -Werror
LDFLAGS =
CC = gcc
LD = gcc
TARG = driver
OBJS = modules.o main.o
#################################################################
# Rules for make
#################################################################
$(TARG): $(OBJS)
$(LD) $(LDFLAGS) $(OBJS) -o $(TARG)
%.o: %.c %.s
$(CC) $(CFLAGS) -c $<
clean:
rm -f *.o *˜ $(TARG)
print:
pr -l60 Makefile modules.c main.c | lpr
#################################################################
# Dependencies -- none in this program
#################################################################
You've already gotten feedback about using GCC and Makefiles, and it's been noted that the typical way to accomplish your task would be two .c files and one .h file. But it's not required to have a .h file if you use function declarations (which is arguably simpler, just less maintainable and useful), as demonstrated by the following below example.
main.c:
void moduleFunc1(int); // extern keyword required for vars, not for functions
int main()
{
moduleFunc1(100);
return 0;
}
module.c:
#include <stdio.h>
void moduleFunc1(int value)
{
printf("%d\n", value);
}
To compile:
gcc main.c module.c
Edit: After having looked at the assignment you linked, my best guess is actually still that function declarations are what you are looking for. To quote from the assignment, under "Others", #7:
A function should be declared in the module/function where
it is called and not in global scope. Say A calls B and C does
not call it then B should be declared in A only.
In my example, the function declaration is in the module where it's called and seems to meet the A-B-C example. (The confusing part is the global scope comment, but I wouldn't say that the function declaration's scope is global. Observe that if you move the declaration below main(), for example, it messes things up. I haven't found something strictly authoritative for this point, though.)
Having read the assignment, could your instructor possibly mean the following?
main.c:
#include <stdio.h>
int main() {
int plus(int a, int b); /* declaration */
printf("%d ", plus(4, 5));
exit(0);
}
module.c:
int plus(int a, int b) {
return a + b;
}
gcc -Wall -Wextra main.c module.c
The thing is though, that plus() is available in the global namespace. So I am a bit lost.
Just an aside:
3. int next = 234;
printf("%6d ", next);
will print value of next, right justified in 6 columns
6. Use separate statements for declaration and initialization
of a variable as:
int xval;
xval = 100;
Do as I say, not as I do!
You can do this a few ways, but regardless of which you choose, if main.c calls functions from module.c, then main.c must #include a header which declares prototypes for those functions.
The first and simplest way is to just do this:
gcc -Wall -g main.c module.c -o myprogram
The second and more ornate way is to build module.c first as an object file. The primary purpose of this method is to save time when developing/debugging/compiling large programs with multiple parts -- rather than having to recompile the whole thing, you can just recompile the parts the have changed. It also allows you to easily mix and match parts. This is easiest to do with a makefile:
myprogram: main.c module.o
CC $(CFLAGS) main.c module.o -o myprogram
module.o:
CC $(CFLAGS) -c module.c
Notice the "myprogram" target from the makefile works with (prereq) module.o whereas the plain gcc method works with module.c.
If, as per your assignment, you can't use a header or global declarations, you can declare prototypes inside functions:
void somefunc () {
char *whatever (int x); // prototype
printf("%s\n", whatever(12));
}
Is fine, and presuming whatever() is defined somewhere, will work when you compile and run it.

Why does CC not see my function definition in header?

I'm writing a simple application in ANSI C. I am using GCC in a Unix environment.
I have the following sample application:
//main.c
#include "foo.h"
int main()
{
int result;
result = add(1,5);
return0;
}
Header:
//foo.h
#ifndef FOO_H_INCLUDED
#define FF_H_INCLUDED
int add(int a, int b);
#endif
Implementation:
//foo.c
int add(int a, int b)
{
return a+b;
}
I am compiling my program with the following command:
cc main.c -o main.o
The compiler complains that 'reference to add is undefined'. Is this a linking problem? How do properly make use of my header?
Thanks!
You need to compile both your source files together:
cc main.c foo.c -o main
Also, in this case, -o produces an executable, so calling it main.o can be misleading.
Yet another tidbit, though unrelated to the question: the #ifndef and #define in foo.h don't match.
The header is not your current problem. Your current problem is that you're not compiling the add function definition in foo.c.
Try
cc main.c foo.c -o main.o
If you are trying to compile main.c into an assembled object file, you need to prevent gcc from trying to link. This is done via
cc -c main.c -o main.o
You can compile all other object files, then when you have all of your object files ready, you simply do
cc main.o obj1.o anotherOBJ.o -o myExecutableBinary
"undefined reference" is a linker error, not a compiler error.
The compiler sees the declaration in the header, but you have not compiled or linked the definition in foo.c. Your title uses the term definition incorrectly.

Resources