I have the following code layout
header.h
#ifndef _header_h
#define _header_h
void empty(float *array, int l)
{
int i;
for (i=1 ; i<=l ; i++)
{
array[i]=0;
}
}
#endif
and two files (lets call them file1.c and file2.c)
#include "header.h"
void function/*1 or 2*/(){
....
empty(a,b);
....
}
So compiling works fine but the linker command fails as the compiler says that there is a duplicate function definition. How can I avoid that with still using the header file? It is working fine when I only define the function in the header and create another .c file containing the full function. I always thought declaring it in the header is the way to go.
I always thought declaring it in the header is the way to go.
Yes, it is. Declaring it in the header is fine. It is not any good to define it in a header, though. (unless it's static inline, but you probably don't want to do that these days.)
You should never have things in a header that require memory in the running program. This is a rough way of specifying it, but it works pretty well in practice.
In other words, the header should only have the prototype for the function, which is a compile-time thing that doesn't "exist" in the running program (unlike the code of the function itself, which of course exists at runtime):
void empty(float *array, int l);
Then put the code in a separate C file, which you compile and link separately.
You have the function empty defined as a global symbol in the header. This means it will be a visible symbol in all compilation units that include it. There are three general workarounds:
make it a static function
static void empty(...) {...}
put the implementation into a separate compilation unit
in header.h:
void empty(float *array, int l);
in empty.c implement it
instruct your linker to ignore duplicate symbols. This differs from linker to linker, consult man ld.
On OS X: -m flag.
On Linux: -z muldefs
Related
I have a c++ header file containing a class.
I want to use this class in several projects, bu I don't want to create a separate library for it, so I'm putting both methods declarations and definitions in the header file:
// example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
namespace test_ns{
class TestClass{
public:
void testMethod();
};
void TestClass::testMethod(){
// some code here...
}
} // end namespace test_ns
#endif
If inside the same project I include this header from more than one cpp file, I get an error saying "multiple definition of test_ns::TestClass::testMethod()", while if I put the method definition inside the class body this does not happen:
// example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
namespace test_ns{
class TestClass{
public:
void testMethod(){
// some code here...
}
};
} // end namespace test_ns
#endif
Since the class is defined inside a namespace, shouldn't the two forms be equivalent? Why is the method considered to be defined twice in the first case?
Inside the class body is considered to be inline by the compiler.
If you implement outside of body, but still in header, you have to mark the method as 'inline' explicitly.
namespace test_ns{
class TestClass{
public:
inline void testMethod();
};
void TestClass::testMethod(){
// some code here...
}
} // end namespace test_ns
Edit
For myself it often helps to solve these kinds of compile problems by realizing that the compiler does not see anything like a header file. Header files are preprocessed and the compiler just sees one huge file containing every line from every (recursively) included file. Normally the starting point for these recursive includes is a cpp source file that is being compiled.
In our company, even a modest looking cpp file can be presented to the compiler as a 300000 line monster.
So when a method, that is not declared inline, is implemented in a header file, the compiler could end up seeing void TestClass::testMethod() {...} dozens of times in the preprocessed file. Now you can see that this does not make sense, same effect as you'd get when copy/pasting it multiple times in one source file.
And even if you succeeded by only having it once in every compilation unit, by some form of conditional compilation ( e.g. using inclusion brackets ) the linker would still find this method's symbol to be in multiple compiled units ( object files ).
These are not equivalent. The second example given has an implicit 'inline' modifier on the method and so the compiler will reconcile multiple definitions itself (most likely with internal linkage of the method if it isn't inlineable).
The first example isn't inline and so if this header is included in multiple translation units then you will have multiple definitions and linker errors.
Also, headers should really always be guarded to prevent multiple definition errors in the same translation unit. That should convert your header to:
#ifndef EXAMPLE_H
#define EXAMPLE_H
//define your class here
#endif
Don't put a function/method definition in an header file unless they are inlined (by defining them directly in a class declaration or explicity specified by the inline keyword)
header files are (mostly) for declaration (whatever you need to declare). Definitions allowed are the ones for constants and inlined functions/methods (and templates too).
Actually it is possible to have definitions in a single header file (without a separate .c/.cpp file) and still be able to use it from multiple source files.
Consider this foobar.h header:
#ifndef FOOBAR_H
#define FOOBAR_H
/* write declarations normally */
void foo();
void bar();
/* use conditional compilation to disable definitions when necessary */
#ifndef ONLY_DECLARATIONS
void foo() {
/* your code goes here */
}
void bar() {
/* your code goes here */
}
#endif /* ONLY_DECLARATIONS */
#endif /* FOOBAR_H */
If you use this header in only one source file, include and use it normally.
Like in main.c:
#include "foobar.h"
int main(int argc, char *argv[]) {
foo();
}
If there're other source files in your project which require foobar.h, then #define ONLY_DECLARATIONS macro before including it.
In use_bar.c you may write:
#define ONLY_DECLARATIONS
#include "foobar.h"
void use_bar() {
bar();
}
After compilation use_bar.o and main.o can be linked together without errors, because only one of them (main.o) will have implementation of foo() and bar().
That's slightly non-idiomatic, but it allows to keep definitions and declarations together in one file. I feel like it's a poor man's substitute for true modules.
Your first code snippet is falling foul of C++'s "One Definition Rule" - see here for a link to a Wikipedia article describing ODR. You're actually falling foul of point #2 because every time the compiler includes the header file into a source file, you run into the risk of the compiler generating a globally visible definition of test_ns::TestClass::testMethod(). And of course by the time you get to link the code, the linker will have kittens because it will find the same symbol in multiple object files.
The second snippet works because you've inlined the definition of the function, which means that even if the compiler doesn't generate any inline code for the function (say, you've got inlining turned off or the compiler decides the function is too big to inline), the code generated for the function definition will be visible in the translation unit only, as if you'd stuck it in an anonymous namespace. Hence you get multiple copies of the function in the generated object code that the linker may or may not optimize away depending on how smart it is.
You could achieve a similar effect in your first code snippet by prefixing TestClass::testMethod() with inline.
//Baseclass.h or .cpp
#ifndef CDerivedclass
#include "Derivedclass.h"
#endif
or
//COthercls.h or .cpp
#ifndef CCommonheadercls
#include "Commonheadercls.h"
#endif
I think this suffice all instances.
I am starting to learn C++ and am getting this compilation error from my IDE (CodeBlocks). I don't understand why this is happening.
|2|multiple definition of `parser::parseFile()'
|2|first defined here|
I don't see how this could happen. This is my entire code base.
main.cpp
#include "parser/parser.cpp"
int main()
{
return 0;
}
parser/parser.cpp
namespace parser {
void parseFile() {
}
}
Assuming you compiled both main.cpp and parser/parse.cpp you clearly have two definitions of parser::parseFile(): the #include directive just become replaced by the content of the named file (you can use the -E flag with your compiler to see the result).
You probably meant to declare parser::parseFile() in a header file (typically with a suffix .h or .hpp or something like that):
// file: parser/parser.hpp
#ifndef INCLUDED_PARSER_PARSER
#define INCLUDED_PARSER_PARSER
namespace parser {
void parseFile();
}
#endif
... and to include this header file into both translation units.
Your program have violated the One Definition Rule (also known as ODR).
In short, parser::parseFile function have been defined in both of your .cpp files, because on the compiler level, #include <header.h> simply means substituting the entire file contents in place.
Solution to your problem depends on your actual program, though. If you want to solve the ODR rule for class definitions, you can do either of:
1) Add a #pragma once at the beginning on a header. This, although being supported by all major compilers, is not standardized way of protecting from double-including a header.
2) Add an include guard:
#ifndef MY_HEADER_GUARD
#define MY_HEADER_GUARD
// your header contents go here
#endif
If you want to solve the ODR problem for functions and data variables, the above approach won't work because you can still have them defined multiple times in different .cpp files.
For this, you still have 2 options:
1) define your function somewhere outside, namely, in some .cpp file, only leaving its declaration in the header:
// header.h
namespace parser {
void func();
}
// file.cpp
void parser::func() { ... }
2) Declare your function as inline, as inline function are allowed to have multiple definitions by the C++ standard (however, they must be strictly identical up to lexem level):
// header.h
namespace parser {
inline void func() { ... }
}
To sum it up, I'd strongly recommend you go both directions by protecting your header from double inclusion and making sure your function is either inline or gets defined in a .cpp file. With the latter, if your function implementation changes, you won't have to recompile all the files that include your header, but only the one that has the functon definition.
Header files ending with .h(usually) is often used to separate class and function declaration from their implementation.
In Code::Blocks you can add header files by right clicking on your project name -> 'Add files' -> create a new file with .h extension. Following good practise, you should also create a .cpp file with the same name where the implementation is written.
As already answered, in your header file you can first write an include guard followed by your include's (if any) and also your function declarations. And in your 'parser.cpp' & 'main.cpp' you will have to #include "parser.h" since the files depend on eachother.
I have a project in code blocks that uses many different files - quite often written by other programmers. At the moment I have a situation in which I have two different sub-projects containing function named in the same manner. Let's say: F(int x). So F(int x) is defined in two source files in two different locations and they have two different headers. Also I have created two different namespaces for those headers:
namespace NS1
{
extern "C"{
#include "header1definingF.h"
}
}
namespace NS2
{
extern "C"{
#include "header2definingF.h"
}
}
But still compiler complains that it has multiple definition of F(int x). How can I workaround this in Code::Blocks (In Visual Studio it works just fine).
EDIT: To be more clear those headers include C code. I haven't thought it will be so messy. There are like thousands of source files using other projects including thousands of functions again... so what to do. I have absolutely no idea how to make it work.
I wonder why it works on Visual Studio, but not on Code Blocks. This suggests you do have an include guard.
Does this help?
Project->Build options...->Linker settings (tab)
-Wl,--allow-multiple-definition
I can't understand your problems clearly, but i think you should understand how the compiler works, when you use gcc to compel your program, your program first will be run include operator, that means if you include a header, the compiler will copy the header file to the file. if you include the header twice there will be a twice define error.so you must guarantee once,you can use
#ifndef __FILE_NAME__
#define __FILE_NAME__
// your code
#endif
If your problem is the redefine the function, you should know how the compiler distinguish the function, i think your problem is you do not use the namespace when you use the function.
The problem is that the namespace do not work for C functions (extern "C").
Here is a simple sample which do not compile:
namespace NS1
{
extern "C"{
int f()
{
return 1;
}
}
}
namespace NS2
{
extern "C"{
int f()
{
return 2;
}
}
}
In this case the two functions are different but have the same name: f(). If you just declare the functions, it will compile but they must refer to the same function.
This second sample works fine. The functions have the name NS1::f() and NS2::f() which are differents.
namespace NS1
{
int f()
{
return 1;
}
}
namespace NS2
{
int f()
{
return 2;
}
}
If you want to use two different c code, you can use objcopy which can help you to have a NS1_f() and NS2_f() function. After that you should rename all functions of the libraries in your includes. In this case, no namespace are used. This is normal, there is no namespace in C. Equivalent functions:
int NS1_f()
{
return 1;
}
int NS2_f()
{
return 2;
}
Short of editing the .cpp files themselves and renaming the functions (which is not a practical solution), your options are either making sure to only include one of the header files with duplicate functions at a time (which could be a huge maintainance problem) or, and this would be my recommendation, make use of namespaces. They will save you a ton of hassle in this situation.
You may need one of two things. The following is called a Header Guard:
#ifndef MYHEADER_H
#define MYHEADER_H
//your header code goes here
#endif
This way the header is only included once per object file that asks for it. However, if you want to have two methods with the same identifier, they have to be part of different Namespaces:
namespace myspace1{
void func(void);
};
namespace myspace2{
void func(void);
};
Other than that, there's not really much else you can do. You shouldn't have two functions with the same name in general. Also, you would have to modify this in the header files that you mentioned.
You are allowed to declare functions as often as you want, however they can only have ONE definition.
I believe you have to edit cpp files as well to nest the two functions into a corresponding namespace. Plus, you have to choose which function you want to call like namespace::function() or you can use using namespace with either of the namespaces you created. Hope this helps!
[Updates #1] It is easier to get confused between the declaration and definition of a function. Remember that you can redeclare non-member functions. Thus, if a header file only contains non-member function declarations, it is safe to include it multiple times in one translation unit (a cpp file). Adding ifndef/define in a header file is a good habit for avoiding potential problems but that is not what resolves your problem.
Your problem is that you want to have two different function definitions with the same function signature(its name and arguments) and that's not allowed in C++. You can either change one of their signatures or put them into a different namespace (which you are trying but without touching their definitions). Both ways require you to edit files containing their definitions.
[Updates #2]
As you updated the question with that the code is in C, I've searched and found this:
What should I do if two libraries provide a function with the same name generating a conflict?
it will surely help you to understand your problem more clearly and find a solution. Good luck!
I'm currently writing a program, and couldn't figure out why I got an error (note: I already fixed it, I'm curious about WHY the error was there and what this implies about including .h files).
Basically, my program was structured as follows:
The current file I'm working with, I'll call Current.cc (which is an implementation of Current.h).
Current.cc included a header file, named CalledByCurrent.h (which has an associated implementation called CalledByCurrent.cc). CalledByCurrent.h contains a class definition.
There was a non-class function defined in CalledByCurrent.cc called thisFunction(). thisFunction() was not declared in CalledByCurrent.h since it was not actually a member function of the class (just a little helper function). In Current.cc, I needed to use this function, so I just redefined thisFunction() at the top of Current.cc. However, when I did this, I got an error saying that the function was duplicated. Why is this, when myFunction() wasn't even declared in CalledByCurrent.h?
Thus, I just removed the function from Current.cc, now assuming that Current.cc had access to thisFunction() from CalledByCurrent.cc. However, when I did this, I found that Current.cc did not know what function I was talking about. What the heck? I then copied the function definition for thisFunction() to the top of my CalledByCurrent.h file and this resolved the problem. Could you help me understand this behavior? Particularly, why would it think there was a duplicate, yet it didn't know how to use the original?
p.s - I apologize for how confusing this post is. Please let me know if there's anything I can clear up.
You are getting multiple definitions from the linker - it sees two functions with the same name and complains. For example:
// a.cpp
void f() {}
// b.cpp
void f() {}
then
g++ a.cpp b.cpp
gives:
C:\Users\neilb\Temp\ccZU9pkv.o:b.cpp:(.text+0x0): multiple definition of `f()'
The way round this is to either put the definition in only one .cpp file, or to declare one or both of the functions as static:
// b.cpp
static void f() {}
You can't have two global functions with the same name (even in 2 different translation units). To avoid getting the linker error define the function as static so that it is not visible outside the translation unit.
EDIT
You can use the function in the other .cpp file by using extern keyword. See this example:
//Test.cpp
void myfunc()
{
}
//Main.cpp
extern void myfunc();
int main()
{
myfunc();
}
It will call myfunc() defined in test.cpp.
The header file inclusion mechanism should be tolerant to duplicate header file inclusions.
That's because whenever you simply declare a function it's considered in extern (global) scope (whether you declare it in a header file or not). Linker will have multiple implementation for the same function signature.
If those functions are truely helper functions then, declare them as;
static void thisFunction();
Other way, if you are using the same function as helper then, simply declare it in a common header file, say:
//CalledByCurrent.h (is included in both .cc files)
void thisFunction();
And implement thisFunction() in either of the .cc files. This should solve the problem properly.
Here are some ideas:
You didn't put a header include guard in your header file. If it's being included twice, you might get this sort of error.
The function's prototype (at the top) doesn't match its signature 100%.
You put the body of the function in the header file.
You have two functions of the same signature in two different source files, but they aren't marked static.
If you are using gcc (you didn't say what compiler you're using), you can use the -E switch to view the preprocessor output. This includes expanding all #defines and including all #includes.
Each time something is expanded, it tells you what file and line it was in. Using this you can see where thisFunction() is defined.
There are 2 distinct errors coming from 2 different phases of the build.
In the first case where you have a duplicate, the COMPILER is happy, but the LINKER is complaining because when it picks up all the function definitions across the different source files it notices 2 are named the same. As the other answers state, you can use the static keyword or use a common definition.
In the second case where you see your function not declared in this scope, its because the COMPILER is complaining because each file needs to know about what functions it can use.
Compiling happens before Linking, so the COMPILER cannot know ahead of time whether or not the LINKER will find a matching function, thats why you use declarations to notify the COMPILER that a definition will be found by the LINKER later on.
As you can see, your 2 errors are not contradictory, they are the result of 2 separate processes in the build that have a particular order.
I currently have a "library-like" .c file (that'll be shown below). I have 2 questions about it:
If I want to see if it compiles well for itself, how can I do it? If I try to gcc it, it will always give a "no main" error, which makes sense, but raises the problem of knowing if a given .c file will compile well or not in "isolation". Can I safely conclude that if the only error raised by the compiler is the "no main" one, my file is fine? An example of where compiling .c files in isolation could be nice would be to determine which includes are in excess, in here.
Is there a point in a simple file like this to define a header with its method / struct declarations and then have such tiny .c file with the code implementation in it?
#ifndef SEMAFOROS
#define SEMAFOROS
#include <signal.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <semaphore.h>
typedef struct {
sem_t* id;
char* nome;
} Semaforo;
inline void lock(Semaforo* semaforo) {
sem_wait(semaforo->id);
}
inline void unlock(Semaforo* semaforo) {
sem_post(semaforo->id);
}
Semaforo* criarSemaforo(char* nome) {
Semaforo* semaforo = (Semaforo*)malloc(sizeof(Semaforo));
semaforo->id = sem_open(nome, O_CREAT, 0xFFFFFFF, 1);
semaforo->nome = nome;
}
void destruirSemaforo(Semaforo* semaforo) {
sem_close(semaforo->id);
sem_unlink(semaforo->nome);
free(semaforo);
}
#endif
Thanks
To compile it without linking (doesn't require a main entry point):
cc -c file.c -o file.o
Even for a small file that defines routines that will be called from other source files you still want a header file. The header file is how the compiler knows the interface to the routines before the linker ties it all together. If you don't have declarations for functions that are external then the compiler has to make assumptions (usually wrong) about the data types of the parameters. You can declare the functions in every source file where they are used, but the point of header files is so that you just do it once in the header file.
The-c option to gcc seems to be what you are missing, which compiles one .c file to a .o file.
The answer to your second question is 'sure'. It's a good habit not to be typing externs into all the .c files that want to use some shared function or another. Every little .h helps.
For the second question, I'd like to know why!
To answer point 2, keeping declarations in a header file helps you avoid situations like the following.
You decide that you need to keep track of your chickens in file.c:
int number_of_chickens;
In file2.c, you decide that it would be a great idea to represent the number of chickens as a double instead of an int, but you forget to update file.c:
extern double number_of_chickens;
double count_chickens() {
return number_of_chickens;
}
void add_to_chickens(double how_many) {
number_of_chickens += how_many;
}
This will compile just fine. The linker will treat number_of_chickens as a name referencing a 4 bit int in file.c, and an 8 bit double in file2.c.
If you call the count_chickens function, it will return garbage (the high 32 bits of the double will be filled in with the contents of int number_of_chickens, the low 32 bits will be undefined - whatever comes after number_of_chickens in memory).
Even worse, when you call add_to_chickens(1) in file2.c, you will write 8 bytes to a 4 byte storage location, surely causing havoc, but not necessarily causing a runtime error (at least, not right away).
If you keep your external declaration in a common header file, you get a compile time error immediately. If you don't, you instead get an unexplained instability 3 months after you ship.