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.
Related
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.
I'm a beginner learning c. I know that use of word "static" makes a c function and variable local to the source file it's declared in. But consider the following...
test.h
static int n = 2;
static void f(){
printf("%d", n);
}
main.c
#include <stdio.h>
#include "test.h"
int main()
{
printf("%d", n);
f();
return 0;
}
My expected result was that an error message will throw up, since the function f and variable n is local to test.h only? Thanks.
But instead, the output was
2
2
EDIT:
If it only works for a compilation unit, what does that mean? And how do I use static the way I intended to?
static makes your function/variable local to the compilation unit, ie the whole set of source code that is read when you compile a single .c file.
#includeing a .h file is a bit like copy/paste-ing the content of this header file in your .c file. Thus, n and f in your example are considered local to your main.c compilation unit.
Example
module.h
#ifndef MODULE_H
#define MODULE_H
int fnct(void);
#endif /* MODULE_H */
module.c
#include "module.h"
static
int
detail(void)
{
return 2;
}
int
fnct(void)
{
return 3+detail();
}
main.c
#include <stdio.h>
#include "module.h"
int
main(void)
{
printf("fnct() gives %d\n", fnct());
/* printf("detail() gives %d\n", detail()); */
/* detail cannot be called because:
. it was not declared
(rejected at compilation, or at least a warning)
. even if it were, it is static to the module.c compilation unit
(rejected at link)
*/
return 0;
}
build (compile each .c then link)
gcc -c module.c
gcc -c main.c
gcc -o prog module.o main.o
You have included test.h in main.c.
Therefore static int n and static void f() will be visible inside main.c also.
When a variable or function is declared at file scope (not inside any other { } brace pair), and they are declared static, they are local to the translation unit they reside in.
Translation unit is a formal term in C and it's slightly different from a file. A translation unit is a single c file and all the h files it includes.
So in your case, the static variable is local to the translation unit consisting of test.h and main.c. You will be able to access it in main.c, but not in foo.c.
Meaning that if you have another .c file including test.h, you'll get two instances of the same variable, with the same name. That in turn can lead to all manner of crazy bugs.
This is one of many reasons why we never define variables inside header files.
(To avoid spaghetti program design, we should not declare variables in headers either, unless they are const qualified.)
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.
I am having trouble calling an external function I wrote in the Pico editor in linux. The program should call an external function and they are both written in C.
#include????
void calcTax()
float calcfed()
float calcssi()
// stub program
#include"FILE2"???or do I use"./FILE2"// not sure which to use here or what extension the file should have. .c or .h and if it is .h do I simply change the file name to file.h?
#include<stdio.h>
#define ADDR(var) &var
extern void calctaxes()
int main()
{
}
I am using gcc to compile but it will not compile. both files are in the same directory and have the .c extension
I am a new student so bear with me.
Normally, when you want a function in one compilation unit to call a function in another compilation unit, you should create a header file containing the function prototypes. The header file can be included in both compilation units to make sure that both sides agree on the interface.
calctax.h
#ifndef calctax_h_included
#define calctax_h_included
void calctaxes(void);
/* any other related prototypes we want to include in this header */
#endif
Note that extern is not required on functions, only global data. Also, since the function takes no arguments, you should put void in the argument list, and you also need a semi-colon at the end of the prototype.
Next, we can include this header file in the .c file that implements the function:
calctax.c
#include "calctax.h"
void calctaxes(void)
{
/* implementation */
}
Finally, we include the same header file in our main .c file that calls the function:
main.c
#include "calctax.h"
int main(int argc, char **argc)
{
calctax();
return 0;
}
You can compile and link these together with
% gcc -o main main.c calctax.c
Normally you don't want to include .c implementation files. The normal thing to do is have two source files that you build into objects:
cc -o file1.o file1.c
cc -o file2.o file2.c
And then link them into an executable at the end:
cc -o example file1.o file2.o
To allow calling functions between the two .c files, you create a header (.h) file that has function declarations for everything you're interested in sharing. For you, that might be something like header.h, containing:
void calcTax(void);
float calcfed(void);
float calcssi(void);
Then, just #include "header.h" from the implementation files where you need to know about those functions.
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.