Not able to handle multiple c files and header files during compilation - c

I read that the C file containing the function definition should be of the same name as the header file. So, i created two files: functions.h, functions.c & lastly the main.c file which calls the functions which are defined inside of the functions.c file.
//functions.h file
void check();
I have declared check function in the header file
//functions.c file
#include <stdio.h>
#include "functions.h"
int main(void){
void check(){
printf("\nThis is a Test\n");
}
return 0;
}
This file contains all the function definition. But one thing i want to clear out is, I saw some another question on stackoverflow of basically the same type but in function file he had just included the header files and function definitions, without main(). Shouldn't that .c file throw an error?
//main.c file
#include "function.h"
#include <stdio.h>
int main(void)
{
check();
return 0;
}
when i open terminal and type the command to compile the code:
clang main.c
I get an error:
Undefined symbols for architecture x86_64:
"_check", referenced from:
_main in heap-22db64.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
May be i haven't compiled functions.c file that's the reason i see this. I am just compiling main.c. I am not sure about this linking error. If i have 35 .c files. Compiling all of them via commandline would be harder task? What should be my approch to deal with these big projects. Having multiple C & header files?

Here's the typical scenario:
// functions.c
void check(void) {
// do stuff
}
Note: just the definition of check, and nothing else. Then a header:
// functions.h
extern void check(void);
Just a declaration. Then the main file:
// main.c
#include "functions.h"
int main(int argc, char *argv[]) {
check();
}

When definitions are provided in another file, you have to specify that like so using the extern keyword:
functions.h:
extern void check();
functions.c:
void check()
{
printf("\nThis is a Test\n");
}

Related

how to compile header files in c in visual studio code

I creating a program in c language and i using the Visual Studio Code for the first time, my functions in the header files don't function. This is my code in main:
#include <stdio.h>
#include "PilhaDinamica.h"
#include "PilhaEstatica.h"
int main()
{
Pilha *p = criaPilha();
return 0;
}
And this is my .h file:
#ifndef PILHADINAMICA_H_INCLUDED
#define PILHADINAMICA_H_INCLUDED
typedef struct Nodo{
char info;
struct Nodo*prox;
} nodo;
typedef struct {
nodo * Topo;
} Pilha;
Pilha * criaPilha();
int pilha_vazia(Pilha *p);
void push(Pilha *p, char times);
char pop(Pilha *p);
#endif
This is my file with the functions:
#include "PilhaDinamica.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Pilha *criaPilha()
{
Pilha *p = (Pilha*) malloc(sizeof(Pilha));
p->Topo = NULL;
return p;
}
And this is shown in my output: "...\AppData\Local\Temp\ccmjk1nS.o:main.c:(.text+0xf): undefined reference to `criaPilha'
collect2.exe: error: ld returned 1 exit status"
what can i do to make it compile correctly?
As a general rule of thumb, header files (*.h) contains declarations (type, variable and function declarations) and source files (*.c) the definitions of those declarations.
At the compilation step, only source files will be compiled (because the definitions are there). A program or library creation is a 2 (actually more, like preprocessing and more but for simplicity we keep it at 2) step process:
creating object files
e.g. gcc -c -o object_file_name.o source_file_name.c
link those object files into an executable or static/shared library
e.g. gcc -o program_or_library_name object_file_1.o object_file_2.o ...
So, in your case you have to call the compiler two times for your source files (with the -c flag) and once to link those created object files into an executable.
Note: If you're using a different compiler other than gcc, have a look at the documentation on how to create object files and link them together.

Using char in different files in C

I have 3 .c files main.c, fun1.c, fun2.c
char buff[50];//in fun1.c
char *arg; //in fun2.c
arg = strstr(buff, "001"); //in fun2.c
I want to print buff in fun2.c but it gives an error buff undeclared, even though I declared it in fun1.h as extern char buff[];
There are functions in fun1.c and fun2.c each
It is hard to say what is wrong with your particular program, but here is an example which links 2 .c files with one .h file.
1. A header file functions.h:
#include <stdio.h>
extern void func();
Where I use extern to provide definitions for another file.
2. Now, a functions.c file which uses this header file:
#include "functions.h"
void func() {
printf("hello");
}
This needs to #include the header file, and use the function void() to print a message.
3. Finally, a main.c file which links it all together:
#include <stdio.h>
#include <stdlib.h>
#include "functions.h"
int main(void) {
func();
return 0;
}
Which also needs function.h as it uses func(). You then can compile the code as:
gcc -Wall -Wextra -g main.c functions.c -o main
You could also look into makefiles, which would reduce this long compilation line to simply make.

Should ANSI C function definition be placed inside header (.h) or source (.c) file?

What are advantages and disadvantages of both approaches?
Source vs. header implementation
Function definition inside source file
Header file sourcefunction.h contains declaration only.
#ifndef SOURCEFUNCTION_H
#define SOURCEFUNCTION_H
void sourcefunction(void);
#endif // SOURCEFUNCTION_H
Source file sourcefunction.c contains definition
#include "sourcefunction.h"
#include <stdio.h>
void sourcefunction(void) { printf(" My body is in a source file\n"); }
Function definition inside header file
Header file headerfunction.h contains definition which is the declaration at the same time.
#ifndef HEADERFUNCTION_H
#define HEADERFUNCTION_H
#include <stdio.h>
void headerfunction(void) { printf(" My body is in a header file\n"); }
#endif // HEADERFUNCTION_H
No source file is needed.
Consumer
File main.c
#include "sourcefunction.h"
#include "headerfunction.h"
int main(void) {
sourcefunction();
headerfunction();
return 0;
}
Why compile many source files?
We have to compile all source files and remember about them during linking.
gcc -c sourcefunction.c
gcc -c main.c
gcc main.o sourcefunction.o
Make can handle file managing but why even bother?
Is separation of interface and implementation always an issue?
It is obvious reason for big projects and teamwork. The designer specifies the interface. The programmers implement functionality.
What about smaller projects and non-formal approach?
Is removing definition from header files always preventing from linker errors?
Let's assume my program is using another module that defines the function with the same name sourcefunction().
#include "sourcefunction.h"
#include "sourcefunction1.h"
#include "headerfunction.h"
int main(void) {
headerfunction();
sourcefunction();
return 0;
}
Different function interface
File sourcefunction1.h
#ifndef SOURCEFUNCTION1_H
#define SOURCEFUNCTION1_H
int sourcefunction(void);
#endif // SOURCEFUNCTION1_H
File sourcefunction1.c
#include "sourcefunction1.h"
#include <stdio.h>
int sourcefunction(void) { int a = 5; return a; }
By compiling main.c, I get a nice compiler error
sourcefunction1.h:4:5: error: conflicting types for 'sourcefunction'
showing me the location of error.
Same function interface
File sourcefunction1.h
#ifndef SOURCEFUNCTION1_H
#define SOURCEFUNCTION1_H
void sourcefunction(void);
#endif // SOURCEFUNCTION1_H
File sourcefunction1.c
#include "sourcefunction1.h"
#include <stdio.h>
void sourcefunction(void) { int a = 5; printf("%d",a); }
Compiler does not mind multiple declarations. I get ugly linker error.
Can header implementation serve as library?
jschultz410 says
If you are writing a library and all your function definitions are in headers, then other people who do segment their development into multiple translation units will get multiple definitions of your functions if they are needed in multiple translation units
Lets' have
File consumer1.c
#include "headerfunction.h"
void consume1(void) { headerfunction(); }
File consumer2.c
#include "headerfunction.h"
void consume2(void) { headerfunction(); headerfunction();}
File twoConsumers.c
extern void consume1(void);
extern void consume2(void);
int main(void) {
consume1();
consume2();
return 0;
}
Let's compile sources.
gcc -c consumer1.c
gcc -c consumer2.c
gcc -c twoConsumers.c
So far, so good. Now, linking.
gcc consumer1.o consumer2.o twoConsumers.o
Linker error: multiple definition of 'headerfunction', of course.
But I can make my library function static.
File headerfunction.h, afterwards.
#ifndef HEADERFUNCTION_H
#define HEADERFUNCTION_H
#include <stdio.h>
static void headerfunction(void) { printf(" My body is in a header file\n"); }
#endif // HEADERFUNCTION_H
It hides the definition from other translation units.
I shouldn't answer this, but I will.
This can create duplicate definitions unless you really only have a single .c file in your project (unwise). Even the header guards won't prevent files the headers from being included multiple times if those multiple times are with different .c files. When the .obj files are linked together, there will be conflicts.
If only the function declaration and not definition is in the header, then only changes to the interface (the function name, parameters or return type) require recompiling dependencies. However, if the entire definition is in the header, then any change to the function requires recompiling all .c and .h files that depend on it, which, in a larger project, can create a lot of unnecessary recompiling.
It's not the convention. Libraries will not use this convention, so you'll be stuck dealing with their header file structure. Other developers will not use this convention, so you can create confusion or annoyance there.

Duplicate symbol in C using Clang

I am currently working on my first "serious" C project, a 16-bit vm. When I split up the files form one big source file into multiple source files, the linker (whether invoked through clang, gcc, cc, or ld) spits out a the error:
ld: duplicate symbol _registers in register.o and main.o for inferred
architecture x86_64
There is no declaration of registers anywhere in the main file. It is a uint16_t array if that helps. I am on Mac OS 10.7.3 using the built in compilers (not GNU gcc). Any help?
It sounds like you've defined a variable in a header then included that in two different source files.
First you have to understand the distinction between declaring something (declaring that it exists somewhere) and defining it (actually creating it). Let's say you have the following files:
header.h:
void printIt(void); // a declaration.
int xyzzy; // a definition.
main.c:
#include "header.h"
int main (void) {
xyzzy = 42;
printIt();
return 0;
}
other.c:
#include <stdio.h>
#include "header.h"
void printIt (void) { // a definition.
printf ("%d\n", xyzzy);
}
When you compile the C programs, each of the resultant object files will get a variable called xyzzy since you effectively defined it in both by including the header. That means when the linker tries to combine the two objects, it runs into a problem with multiple definitions.
The solution is to declare things in header files and define them in C files, such as with:
header.h:
void printIt(void); // a declaration.
extern int xyzzy; // a declaration.
main.c:
#include "header.h"
int xyzzy; // a definition.
int main (void) {
xyzzy = 42;
printIt();
return 0;
}
other.c:
#include <stdio.h>
#include "header.h"
void printIt (void) { // a definition.
printf ("%d\n", xyzzy);
}
That way, other.c knows that xyzzy exists, but only main.c creates it.

Duplicate Symbol in C

I have two source files:
Source FIle 1 (assembler.c):
#include "parser.c"
int main() {
parse_file("test.txt");
return 0;
}
Source File 2 (parser.c):
void parse_file(char *config_file);
void parse_file(char *src_file) {
// Function here
}
For some reason, when compiling it is giving me the following error:
duplicate symbol _parse_file in ./parser.o and ./assembler.o for architecture x86_64
Why is it giving me a duplicate symbol for parse_file? I am just calling the function here... No?
First off, including source files is a bad practice in C programming. Normally, the current translation unit should consist of one source file and a number of included header files.
What happens in your case is that you have two copies of the parse_file function, one in each translation unit. When parser.c is compiled to an object file, it has its own parse_file function, and assembler.c also has its own.
It is the linker that complains (not the compiler) when given two object files as an input, each of which contains its own definition of parse_file.
You should restructure your project like this:
parser.h
void parse_file(char *);
parser.c
void parse_file(char *src_file) {
// Function here
}
assembler.c
/* note that the header file is included here */
#include "parser.h"
int main (void) {
parse_file("test.txt");
return 0;
}
You're including the parser.c file, which means all the code that is in that file will be "copied" to assembler.c file. That means that the entire contents of parser.c will be compiled when the compiler is compiling parser.c, and then it'll be compiled again when the compiler is compiling assembler.c
That's what headers are for.
In the header you can put only the declarations, so you can include it without creating the same symbols again in a different translation unit.
so you can just create a parser.h containing just the declaration of the function:
void parse_file(char *config_file);
then in your assembler.c you include just the header:
#include "parser.h" //include the header, not the implementation
int main() {
parse_file("test.txt");
return 0;
}
You are including the .c file which contains the definition of the function parse_file. Thus it is defined twice, once in each translation unit, which is not allowed.
As other answers state, including the source means the file will be copied to parser.c and will be defined there as well in the original place (assembler.c). To solve this, either create a header file with your prototype:
parser.h
void parse_file(char *config_file);
And include that file:
assembler.c
#include "parser.h"
int main() {
parse_file("test.txt");
return 0;
}
Or remove the include and provide a clue to the function:
int main() {
void parse_file(char *);
parse_file("test.txt");
return 0;
}
Or even simply remove the include at al. Not good practice, as the compiler (without information on a function) will consider its returned value is an integer and may cause other warnings.

Resources