I have the following program setup:
// main.c
#include "str.h"
...
trim("Hello");
// str.h
char* trim(char* str) {
return str;
}
// str.c
#include "str.h"
[empty]
And compiled as: $ gcc main.c str.c -o run && ./run, and I get the following error:
/tmp/ccEUb8mH.o: In function `trim':
str.c:(.text+0x0): multiple definition of `trim'
/tmp/ccCiyN5A.o:main.c:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
However, as soon as I change str.h/c to the following declration/definition it works:
// str.h
[empty]
// str.c
#include "str.h"
char* trim(char* str) {
return str;
}
What's the reason the second version works but the first one does not?
I suppose it has to do with that the following will work fine:
char * trim(char * str);
char * trim(char * str);
char * trim(char * str);
char * trim(char * str);
char * trim(char * str);
But with definitions it will not:
char * trim(char * str){return str};
char * trim(char * str){return str};
error: redefinition of ‘trim’
When you define a function in a header file, every source file that includes it will have a definition of that function. And for each source file you compile, it creates an object file containing the function definition. Then when you link those source files together to make an executable, you have multiple definitions of the function which gives you the error.
In your example you compiled and linked in one step, however the object files for each source file are still created as temporary files before being linked.
By putting the definition of trim in str.c, you only have a single definition for it in one file, while the header has a declaration that other modules can use to know how to call the function.
Apart from that it is common practice to put definitions in header files and implementations in source files, there is another way to circumvent the problem:
#ifndef HEADER_H
#define HEADER_H
// header.h contents go here ...
#endif
When the header is included the first time ,HEADER_H is not defined yet, so it will get defined, and the functions / variables will be defined. When the header is included the second time, HEADER_H is already defined, and the whole part of code that is in the ifdef - endif part will be skipped. Though you should put your definitions in the header file, and the implementations into the source file, you should put such a guard into your header files all the same. Note that HEADER_H must be replaced with a different name in each header, normally you just take the name of the header file and replace all minuses - and dots . with an underscore _ .
The reason is linker(ld) sees two definitions of trim function, one from main.c and other from str.c, because the header file is included in both files.
// main.c
#include "str.h"
...
trim("Hello");
the above is equal to
// main.c
char* trim(char* str) {
return str;
}
...
trim("Hello");
and in //str.c you are including str.h , so the str.c contents will be, after inclusion of header contents.
//str.c
char* trim(char* str) {
return str;
}
Now when you issue command: gcc main.c str.c -o run && ./run
str.c:(.text+0x0): multiple definition of `trim'
/tmp/ccCiyN5A.o:main.c:(.text+0x0): first defined here
In the error compiler (precisely the linker) clearly pointed out two definitions of trim.
So, defining functions in header files is not a good practice, there are few scenarios people do that but we need to take care when using, else we will be facing these multiple definitions errors.
Whenever you use #include with any file it's inserted at the spot where your include is. So
// foo.h
void a(char b) {
// code
}
// main.c
#include "foo.h"
// main code
Is equivelent to
// main.c
void a(char b) {
// code
}
// main code
However, nothing stops you from including foo.h multiple times. This causes redefinition errors, which you get in your case. Putting function definitions in your .c file insures it's only included the one time. You can redaclare templates though, so it's common to put something like void a(char b); in your .h file.
Related
I have a header file , "temp.h" ,and several ".c" files which has "#include <temp.h>" header statements in each of them. And I define a global static char array in "temp.h" file as follows:
temp.h
static char buffer[1000]={'A','B','C','\0'};
main.c
...
#include <temp.h>
int main()
{
strcpy(buffer,"xyz");
printf("\nBuffer : %s",buffer);
func();
return 0;
}
other.c
...
#include <temp.h>
int func()
{
printf("\nInside func(), buffer : %s",buffer);
return 0;
}
and I compile all files with following command:
gcc -o output.o main.c other.c
And I get no errors... and when run the "output.o" program ,
I expect a result like this:
Buffer : xyz // Buffer was intentionally changed inside main
Inside func(), buffer : xyz
but I get:
Buffer : xyz // Buffer was intentionally changed inside main
Inside func(), buffer : ABC // doesn't get updated buffer content- why?
Why when I change the contents of a "(supposedly)global" static char array in one file inside any function scope (main or anyother), this change doesn't get reflected to all this char array's future references from any other file later, but instead in each file((or maybe inside in each function) its content is preserved??
How to make such that, I can use a specific part of char array (memory region) which is GLOBALLY accessible from all "files" and in their functions, and all references get correct readings?
thnx
With your current approach you have two copies of the array. Instead you need to declare the array in temp.h (with extern instead of static) and define it elsewhere, for instance in in temp.c:
temp.h:
#ifndef TEMP_H
#define TEMP_H
extern char buffer[1000];
#endif
temp.c:
#include "temp.h"
char buffer[1000] = "ABC";
You can also probably find a more descriptive name than temp for the module. It is also a good idea to add a prefix to the buffer variable, e.g. temp_buffer so that you avoid potential name clashes and make it easier for yourself and others to find where the array is declared.
Ok...GOT IT!... now I solved!
In a singly included header file (( which is temp.h in question )) u must write:
extern char buffer[];
Note: single inclusion of this temp.h file can be achieved by "#ifndef-#endif" pairs in other ".c" and ".h" files of the compilation.
And next, include only in one of the files the following statement of definition:
char buffer[1000];
I hope this solution helps some guys.
I have 3 projects: Server, Client and Commons. Making header & source pairs in Commons doesn't cause any problems and I can access the functions freely from both Server and Client.
However, for some reason making additional source/header files within Server or Client project always causes multiple definition of (...) and first defined here errors.
Example:
commands.h (in root dir of the Client project)
#ifndef COMMANDS_H_
#define COMMANDS_H_
#include "commands.c"
void f123();
#endif /* COMMANDS_H_ */
commands.c (in root dir of the Client project)
void f123(){
}
main.c (in root dir of the Client project)
#include "commands.h"
int main(int argc, char** argv){
}
Errors:
make: *** [Client] Error 1 Client
first defined here Client
multiple definition of `f123' commands.c
Cleaning, rebuilding index, rebuilding projects doesn't help. Neither does restarting the computer.
The problem here is that you are including commands.c in commands.h before the function prototype. Therefore, the C pre-processor inserts the content of commands.c into commands.h before the function prototype. commands.c contains the function definition. As a result, the function definition ends up before than the function declaration causing the error.
The content of commands.h after the pre-processor phase looks like this:
#ifndef COMMANDS_H_
#define COMMANDS_H_
// function definition
void f123(){
}
// function declaration
void f123();
#endif /* COMMANDS_H_ */
This is an error because you can't declare a function after its definition in C. If you swapped #include "commands.c" and the function declaration the error shouldn't happen because, now, the function prototype comes before the function declaration.
However, including a .c file is a bad practice and should be avoided. A better solution for this problem would be to include commands.h in commands.c and link the compiled version of command to the main file. For example:
commands.h
#ifndef COMMANDS_H_
#define COMMANDS_H_
void f123(); // function declaration
#endif
commands.c
#include "commands.h"
void f123(){} // function definition
I had a similar issue when not using inline for my global function that was included in two places.
You should not include commands.c in your header file. In general, you should not include .c files. Rather, commands.c should include commands.h. As defined here, the C preprocessor is inserting the contents of commands.c into commands.h where the include is. You end up with two definitions of f123 in commands.h.
commands.h
#ifndef COMMANDS_H_
#define COMMANDS_H_
void f123();
#endif
commands.c
#include "commands.h"
void f123()
{
/* code */
}
Maybe you included the .c file in makefile multiple times.
I am adding this A because I got caught with a bizarre version of this which really had me scratching my head for about a hour until I spotted the root cause. My load was failing because of multiple repeats of this format
<path>/linit.o:(.rodata1.libs+0x50): multiple definition of `lua_lib_BASE'
<path>/linit.o:(.rodata1.libs+0x50): first defined here
I turned out to be a bug in my Makefile magic where I had a list of C files and using vpath etc., so the compiles would pick them up from the correct directory in hierarchy. However one C file was repeated in the list, at the end of one line and the start of the next so the gcc load generated by the make had the .o file twice on the command line. Durrrrh. The multiple definitions were from multiple occurances of the same file. The linker ignored duplicates apart from static initialisers!
This error can also occur if the definitions are "header file only".
Example :
foo.h :
#ifndef FOO
#define FOO
int myFunc(int a) {
return a+2;
}
#endif
// There is no foo.c
// Main source files
file1.c :
#include "Foo.h"
<some code>
file2.c :
#include "Foo.h"
<some code>
Now both file1.c and file2.c contains definition of myFunc(). This will cause linker error when they are getting linked to same library.
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.
// File foo1.c :
#include <stdio.h> // once
void foo1(void);
void foo1(void){
puts("foo1");
}
// File foo2.c :
#include <stdio.h> // again
void foo2(void);
void foo2(void){
puts("foo2");
}
// File foomain.c :
#include <stdio.h> // yet again
void foo1(void); // again
void foo2(void); // again
int main(void){
foo1();
foo2();
puts("foomain");
return 0;
}
// create object files
gcc -fPIC foo1.c -o foo1.o // 1 stdio.h
gcc -fPIC foo2.c -o foo2.o // 1 stdio.h
// create shared library
gcc -fPIC -shared foo1.o foo2.o -o foo.so // foo.so contains stdio.h 2 times ?
// build entire program
gcc foo.so foomain.c -o foomain // foomain contains 1 stdio.h plus the 2 from foo.so ?
Why does the entire program contain 3 stdio.h ? Seems redundant, why not just 1 ? Shouldn't the compiler need only 1 ?
It makes sense for the object files to contain a prototype but why do they have to be specified again in foomain.c ? Shouldn't the compiler know they are already specified in foo.so ?
That's because each file is compiled separately, so each time the compiler should know the signatures of all functions used to perform compile-time checks. So, each file has to contain all declarations used, which are included by the preprocessor before the file is compiled.
If you look at the top of most header files they have an include guard to stop double inclusion.
#ifndef FOO
#define FOO
#endif
See Include Guard for more information.
The #include lines are not actually a part of the compiler, but the C preprocessor.
What the preprocessor does with #include lines is to actually include the file into the source, and creates a new temporary file containing the contents of your file with the #include line replaced by the contents of the file being included.
You don't actually need the include file at all, if all you are doing is calling functions. You might get warnings about the functions not being declared, but those can be adding the prototypes for those functions yourself. For example, in your main source file you only use puts, instead of including <stdio.h> you can add a prototype like this:
int puts(const char *s);
However, <stdio.h> also defines some structures (like the FILE structure) and declares some variables (like stdout) and if you use any of those you need the header file as well.
You can use include guards as #Jeff suggested or just put #pragma once at the top of each header.
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.