Using a function from another C file placed in another directory? - c

Say I have a parent directory A with two subdirectories B and C.
Sub-directory C has a helper.c and helper.h as shown:
//helper.c
void print(){
printf("Hello, World!\n");
}
//helper.h
void print();
Now, in sub directory B, I have a main.c which just calls the print function:
//main.c
#include<stdio.h>
#include"../C/helper.h"
void main(){
print();
}
I tried the following commands for compiling main.c:
Command 1: gcc main.c //Gives undefined reference to 'print' error
Command 2: gcc main.c ../C/helper.c //Compiles successfully
Now I removed the #include"../C/helper.h" from main .c and tried the Command 2 again. It still works.
So I have the following questions:
i) What difference does it make whether the helper.h file is included or
helper.c?
ii) Why command 1 fails?
iii) Is there a way to compile my C program without having to specify
helper.c everytime?

What happens when you execute:
Command 1: gcc main.c //Gives undefined reference to 'print' error
When execute gcc main.c
Compiler compiles main.c and creates objective file. This file will contain unresolved link to function print(). Because there is no implementation of function print() in main.c file.
After compilation gcc tries to make full executable file. To do this gcc combines all objective files and tries to resolve all unresolved links. As you remember there is unresolved link for function print(), gcc can't find implementation and raise the error.
When you execute
Command 2: gcc main.c ../C/helper.c //Compiles successfully
gcc compiles both files. Second file ../C/helper.c contains implementation of function print(), so linker can find it and resolve reference to it in function main().
i) What difference does it make whether the helper.h file is included or helper.c?
In your case helper.h contains forward declaration of function print(). This gives information to compiler how to make call of function print().
ii) Why command 1 fails?
See above.
iii) Is there a way to compile my C program without having to specify helper.c everytime?
Use make utility. Compile helper.c in separate objective file helper.o and use it in linkage command.
helper.o: ../C/helper.c ../C/helper.h
gcc -c ../C/helper.c
main.o: main.c main.h
gcc -c main.c
testprog: main.o helper.o
g++ main.o helper.o -o testprog
See make utility manual for details.
Commands should be indented by TAB.

First you need to understand that #include simply adds whatever text is in the #include parameter to the position in the file the statement is in, for example:
//file1.h
void foo();
//main.c
#include "file1.txt"
int main(int argc, char **argv)
{
foo();
return 0;
}
Will cause the pre-compilation to generate this unified file for compilation:
//main.c.tmp
void foo();
int main(int argc, char **argv)
{
foo();
return 0;
}
So to answer your first and second questions:
When you include a header file (or any file) that only contains declarations (i.e function signatures) without definitions (i.e function implementations), as in the example above, the linker will fail in finding the definitions and you will get the 'undefined reference' error.
When you include a c code file (or any file) that contains definitions, these definitions will be merged to your code and the linker will have them, that's why it works.
and as for your third question
It is bad practice to include c files directly in other c files, the common approach is to keep separate c files with headers exposing the functionality they provide, include the header files and link against the compiled c files, for example in your case:
gcc main.c helper.c -o out
Will allow you to include helper.c in main.c and still work because you instructed the compiler to compile both files instead of just main.c so when linking occurs the definitions from the compilation will be found and you will not get the undefined behavior error
This is, in a nutshell. I abstracted a lot of what's going on to pass on the general idea. this is a nice article describing the compilation process in fair detail and this is a nice overview of the entire process.

I'll try to answer:
i) What difference does it make whether the helper.h file is included or helper.c?
When you include a file, you don't want to expose your implementation, hence its better to include h files, that contains only the "signatures" - api of your implementation.
ii) Why command 1 fails?
When you compile you must add all your resources to the executable, otherwise he won't compile.
iii) Is there a way to compile my C program without having to specify
helper.c everytime?
You can use Makefile to compile your program. Maybe this tutorial can help you.

i) What difference does it make whether the helper.h file is included
or helper.c?
Including helper.c means that helper.c gets compiled each time as if it were part of main.c
Including helper.h lets the compiler know what argument types the function print() takes and returns so the compiler can give an error or warning if you call print() incorrectly
ii) Why command 1 fails?
The compiler is not being told where to find the actual code for the print function. As explained, including the .h file only helps the compiler with type checking.
iii) Is there a way to compile my C program without having to specify
helper.c everytime?
You can compile it once into an object file and optionally you can add that obj to a static or dynamically loaded library. You still need to help the compiler find that obj or library. For example,
gcc -c helper.c
gcc main.c helper.o
The correct way to avoid compiling modules that don't need compiling is to use a Makefile. A Makefile compares when a module was last compiled compared to when it was last modified and that way it knows what needs to be compiled and what doesn't.

Related

Why I got "clang: error: cannot specify -o when generating multiple output files"?

I am a newbie in C. I have two simple source code files f1.c and f2.c.
f1.c looks like:
#include <stdio.h>
#include "f.h"
void f1(void) {
// some code ...
}
function f2() in f2.c relies on f1() in f1.c.
#include <stdio.h>
#include "f.h"
void f2(void) {
f1();
}
f1.c and f2.c share a same header f.h,
void f1(void);
void f2(void);
There are no main() access, I just want to compile these two file into a .o file without linker (using -c option),
gcc -c f1.c f2.c -o f2.o
then I got,
clang: error: cannot specify -o when generating multiple output files
but when I mentioned only f2.c, it works well,
gcc -c f2.c -o f2.o
So what's the problem? Thanks!
You should look into the compilation process for C. The first stage is compiling the .c source code into .o object files. The .c files do not need to see the other .c files; they are accepting as fact what you've told them about the existence of external functions. It's not until the linker comes in that it really needs to see the function because the implementation details don't matter to your .c file, just the interface, which you've presumably given it in the header.
What you can do, if you like, is drop the -o flag specifying the output file you want to create. Just compile with
gcc -c f1.c f2.c
and it will know to create f1.o and f2.o which will be able to link against each other when the time comes that you do want to go through with the linking process.
I am curious, however, what your intentions may be for wanting to compile these without linking. I only ask as you refer to yourself as a newbie, so I am wondering if maybe there is an end goal you have in mind and perhaps aren't asking the right question.

How to organize Header files

Using header files in this way gives me the error "undefined reference to somefunc". What is the proper way to make sure somefunc.c is seen so this error doesn't occur? It seems simply including somefile.h in main.c isn't enough to see the definitions in somefile.c
main.c
#include "somefile.h"
int main() {
somefunc();
return 0;
}
somefile.h
#ifndef SOMEFILE_H
#define SOMEFILE_H
void somefunc();
#endif
somefile.c
#include <stdio.h>
#include "somefile.h"
void somefunc() {
printf("hello\n");
}
I don't understand why I am getting errors because this is the same manner in which they are used in tutorials and videos i've been viewing while looking for an answer. The code above is an answer given earlier but it is still has the same error.
Undefined reference to somefunc is a linker error, not a compiler error.
This means that, although when compiling main.c the header somefile.h is found, you are not compiling the file somefile.c together with main.c. So when linking occurs the linker is not able to find the implementation of somefunc in any object file to resolve the call from main().
If you are using GCC or Clang just compile both source files to your command, eg
gcc somefunc.c main.c -o output
If you are using an IDE instead, make sure that somefile.c is compiled together with main.c when building the application.
This doesn't appear to be a problem with the header file.
This appears to be a problem in linking, which depends on how you build the project. If you use an IDE, it means that somefile.c is not included in the project. If you're using make and a makefile, it means that somefile.c is not listed in the makefile, or at least not included for the linker. If you're building at the command line (not using make or some build tool, but using gcc), then you're not including somefile.c in the command.
The undefined reference error means the linker couldn't find the code in somefile.c, because the linker didn't know to include it.

Undefined reference to functions C

I downloaded a library from here. I added the header file in my program but when I try to access the functions of this header file, I get error:
undefined reference to the function for u_open() and u_accept(). I tried to compile the .c files of this header file but I get this error:
undefined reference to main.
I tried everything in my knowledge to solve this issue, but couldn't solve it. Here is the program.
#include "uici.h"
int main()
{
char client[50];
char buf[1024];
u_port_t portnumber;
portnumber=48625;
int fd = u_open(portnumber);
int communFd = u_accept(fd,client,50);
perror("Opened");
fprintf(stderr,"\nComun fd is %d\n\n\n",communFd);
read(communFd,buf,1024);
write(STDOUT_FILENO,buf,1024);
fprintf(stderr,"\n\nReading complete\n");
return 0;
}
What can I do to solve this problem?
Regards
Your header file uici.h declares the functions you're calling in main() (u_open() and u_accept()), but not their implementations, which are in the source files. When the linker tries to create the entire program, it then complains that the implementations can't be found.
The solution is to link all the files together when creating the actual program binary. When using the g++ frontend, you can do this by specifying all the source files together on the command line. For example:
g++ -o main main.c uici.c
will create the main program called "main", assuming that the implementations you need are in uici.c.
edit: In the case you're linking against a prebuilt library for uici, you'll need to specify to the frontend that the library is needed for linking, e.g. with:
g++ -o main main.c -luici
You need to link the library when using gcc like :
gcc nameofprgram.c -l<library>
Use any of these flags while compiling with gcc
-I <searchpath to include files>
-L <searchpath to the lib file>
-l<thelibname>
Ex:
gcc -o myprogram -lfoo -L/home/me/foo/lib myprogram.c
This will link myprogram with the static library libfoo.a in the folder /home/me/foo/lib

Functions and header files (ansi c)

This is a question from job interview.Let's say we have "a.c" source file with some function and "a.h" as its header file.Also we have main.c file which calls that function.Now let's suppose we have "a.h" and "a.o"(object file) and a.c is unavailable.How do we call this function now?
(I had a hint that we need to use function pointers.Another hint is to do this using pre-compiler directives such as #define and #ifndef).
Also i would like to know how in .h file we know if we are linked properly to source file?
Thank You
Just include a.h from main.c and you can use the functions declared in a.h. Then just compile it with the same compiler version as a.o is build:
gcc -c main.c
gcc main.o a.o
To compile main.c, you need the function definition. You already have that in a.h. So you would write:
// main.c
#include "a.h"
int main()
{
foobar(); // Let's say this is the function from a.h
}
When compiling it, you would have to include the object file at the linking stage. So using gcc...
gcc -c main.c // Compile main.c to main.o
gcc -o main main.o a.o
No function pointers or macros needed.
The way you describe it, you only need a header file to call the function. The header file contains the prototype of the function, which allows the compiler to know what the signature of the function is.
You would then link in your object file (which contains the compiled version of function) and everything would be OK.
I don't know why you would need functions pointers or pre-compiler directives. Maybe you didn't understand the question 100%?
In main.c, call the function as normal.
Then compile main.c to main.o. gcc -c main.c
Then link a.o and main.o. gcc main.o a.o
Something about this question sounds garbled. How you write the function call in main depends solely on its declaration in a.h. The presence or absence of a.c doesn't change that. Certainly nothing involving macros or function pointers.
Compiling and linking are two distinct steps; the compiler checks that you're passing the right number and types of arguments and assigning the result to the right type of object based on the function's declaration, while the linker attempts to resolve the reference to the function's implementation in the machine code.
The result of compiling and linking is a binary sludge that may or may not have any obvious relationship to the original source code1. Debug versions preserve varying levels of information to support source-level debuggers, but you can pretty much rely on release versions not preserving any useful source information.
1. Every now and again someone asks for a tool to recover source code from an executable; this is often described as attempting to turn hamburger back into cows.

Including source files in C

So I get the point of headers vs source files. What I don't get is how the compiler knows to compile all the source files. Example:
example.h
#ifndef EXAMPLE_H
#define EXAMPLE_H
int example(int argument); // prototype
#endif
example.c
#include "example.h"
int example(int argument)
{
return argument + 1; // implementation
}
main.c
#include "example.h"
main()
{
int whatever;
whatever = example(whatever); // usage in program
}
How does the compiler, compiling main.c, know the implementation of example() when nothing includes example.c?
Is this some kind of an IDE thing, where you add files to projects and stuff? Is there any way to do it "manually" as I prefer a plain text editor to quirky IDEs?
Compiling in C or C++ is actually split up into 2 separate phases.
compiling
linking
The compiler doesn't know about the implementation of example(). It just knows that there's something called example() that will be defined at some point. So it just generated code with placeholders for example()
The linker then comes along and resolves these placeholders.
To compile your code using gcc you'd do the following
gcc -c example.c -o example.o
gcc -c main.c -o main.o
gcc example.o main.o -o myProgram
The first 2 invocations of gcc are the compilation steps. The third invocation is the linker step.
Yes, you have to tell the compiler (usually through a makefile if you're not using an IDE) which source files to compile into object files, and the compiler compiles each one individually. Then you give the linker the list of object files to combine into the executable. If the linker is looking for a function or class definition and can't find it, you'll get a link error.
It doesn't ... you have to tell it to.
For example, whe using gcc, first you would compile the files:
gcc file1.c -c -ofile1.o
gcc file2.c -c -ofile2.o
Then the compiler compiles those files, assuming that symbols that you've defined (like your example function) exist somewhere and will be linked in later.
Then you link the object files together:
gcc file1.o file2.o -oexecutable
At this point of time, the linker looks at those assumtions and "clarifies" them ie. checks whether they're present. This is how it basically works...
As for your IDE question, Google "makefiles"
The compiler does not know the implementation of example() when compiling main.c - the compiler only knows the signature (how to call it) which was included from the header file. The compiler produces .o object files which are later linked by a linker to create the executable binary. The build process can be controlled by an IDE, or if you prefer a Makefile. Makefiles have a unique syntax which takes a bit of learning to understand but will make the build process much clearer. There are lots of good references on the web if you search for Makefile.
The compiler doesn't. But your build tool does. IDE or make tool. The manual way is hand-crafted Makefiles.

Resources