How to resolve Duplicate Symbol Error? - c++

I'm compiling 2 C++ files together. 4 if you include the header files. The problem is, I keep getting "Duplicate Symbol" errors when the linker tries to link the files together.
Here are my files.
main.h
int test2();
main.cc
#include "main.h"
#include "test.h"
int test2(int test) {
return 0;
}
int main() {
test2(test());
return 0;
}
test.h
int hello = 10;
int test();
test.cc
#include <iostream>
#include "test.h"
using namespace std;
int test() {
cout << hello << endl;
return 0;
}
I think I'm doing something simple wrong. Can someone please point out what I'm doing wrong.
Here's how I'm compiling the files.
c++ main.cc test.cc -o main
Here's the error I get:
duplicate symbol _hello in:
/var/folders/nj/568_95bj4dg9v11l_mksv_2m0000gn/T/main-3becdd.o
/var/folders/nj/568_95bj4dg9v11l_mksv_2m0000gn/T/test-e84473.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

In header file, declare the variable:
extern int hello;
In exactly one source file, define the variable:
int hello = 10;
Do not define variables in headers - that's equivalent to defining them in every source file that includes the header, and that's what's causing your linker error.

You can simply define hello as a "static" (global) variable
static int hello = 10;
More information is mentioned in a similar question:
Duplicate symbols while linking

Related

Can't link header files to my main.cpp in VScode (macOS) (clang error)

I am trying to link a header file which has a class defined in it and a .cpp file that has the actual functions of that class to my main cpp file but I'm getting this error:
c++ DataMembers.cpp -o DataMembers
Undefined symbols for architecture x86_64:
"Cat::eat()", referenced from:
_main in DataMembers-053507.o
"Cat::meow()", referenced from:
_main in DataMembers-053507.o
"Cat::sleep()", referenced from:
_main in DataMembers-053507.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [DataMembers] Error 1
Please note that all files exists in the same directory!
my main.cpp code is:
#include "Cat.h"
#include <iostream>
using namespace std;
int main()
{
Cat myCat;
myCat.eat();
myCat.meow();
myCat.sleep();
}
my Cat.h code:
#ifndef CAT_H_
#define CAT_H_
class Cat
{
public:
void meow();
void sleep();
void eat();
};
#endif
and Cat.cpp code is:
#include <iostream>
#include "Cat.h"
using namespace std;
void Cat::meow()
{
cout << "Meowwwwww!" << endl;
return;
}
void Cat::sleep()
{
cout << "Zzz ... " << endl;
return;
}
void Cat::eat()
{
cout << "Num Nom Nom .. Yummy" << endl;
return;
}
Interesting thing is when I change the header file in my main.cpp from #inclue "Cat.h"
into #include "Cat.cpp" the program compiles without any issues! I just don't know why?
I have searched for a solution but couldn't find any yet! and I need to be able to use header files I create myself!
Thank you in advance friends!
When compiling make sure that you reference all the cpp source files so it can generate the according object files.
It seems like you forgot to reference cat.cpp. The compiler sees that you have a header file included, assuming the implementation of this class will be in another cpp file. Because you forgot to reference the said file, the linker will complain that some undefined symbols cannot be linked.
Once you included the cat.cpp directly into your main.cpp, you basically copied all its contents to this file, which means there is no need anymore to link the implementation from another translation unit.
In short: you need to tell your compiler about cat.cpp
First Check For Which Architecture You Have Written the Header File For, If it is the Same Architecture as the Main File, Then Try Using Full Path From the Drive, Even then It is Not Working, Add Your Header File Path as an Additional Include Directories.
try this in main.cpp
#include "Cat.cpp"
instead of:
#include "Cat.h"
source:
How to create a C++ project in VS Code and link main, functions and header?
In Cat.cpp you wrote #include "cat.h" but the file name is "Cat.h" so you messed up the capitalization.

c++ include header get failed

recently I've started learning c++. When I tried to write my header file, I got include error. Here is my code:
First is the header file(header.h)
#pragma once
void print(int);
and then is its cpp file(header.cpp)
#include "header.h"
#include <iostream>
using namespace std;
void print(int x){
cout << x << endl;
}
and finally my main cpp program(main.cpp)
#include <iostream>
#include "./header.h"
using namespace std;
int main(){
int x = 123;
print(x);
}
Here is the error, I can't figure out what it's saying orz
cd "/Users/yianchen/Desktop/cpp practice/" && g++ main.cpp -o main &&
"/Users/yianchen/Desktop/cpp practice/"main Undefined symbols for
architecture x86_64: "print(int)", referenced from:
_main in main-90c620.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to
see invocation)
I have searched for some solution, when I use
#include "header.cpp"
It works fine, but I see guys unrecommended using #include some_file.cpp
By the way, I use visual studio code and use code runner. Thanks!
The easiest solution would be to do something like the following
g++ header.cpp main.cpp
This will make sure that the function defined in header.cpp is compiled together with the code that uses it.
Normal usage would be to compile header.cpp, not to include it in another .cpp source. Then the linker will put the pieces together.

C++ linker error despite using g++, clang etc to compile

I'll start by showing you the error I have been getting:
Henrys-MacBook-Pro-2:assignment1 HenryDashwood$ clang++ main.cpp
Undefined symbols for architecture x86_64:
"clear()", referenced from:
_main in main-a61991.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
I've been trying to move some functions into a source.cpp file with prototypes in a header.h file. The code works fine when I have it all in the main.cpp file. It also works when I move the function prototype to a header file. However, when I then also move the functions to the source file, it errors me! Here are the relevant bits of my code:
main.cpp
#include <string>
#include <iostream>
using namespace std;
#include "header.h"
int main()
{
char quit, choice;
int term, day, hour;
string termName, dayName;
clear();
return 0;
}
header.h
#define TERMS 4
#define DAYS 7
#define HOURS 8
struct TTcell
{
string subject;
string lecturer;
string roomName;
};
struct TTcell timetables[8][7][4];
void clear();
source.cpp
#include <string>
#include <iostream>
using namespace std;
#include "header.h"
void clear()
{
for (size_t i = 0; i < TERMS; i++) {
for (size_t j = 1; j <= DAYS; j++) {
for (size_t k = 1; k <= HOURS; k++) {
timetables[k][j][i].subject = "";
timetables[k][j][i].lecturer = "";
timetables[k][j][i].roomName = "";
}
}
}
}
This is an example using one function to keep the question readable. They all seem to have the same affliction. I saw on other posts people got similar errors because of the compiler they were using. I've tried c++, g++ and clang++, all to no avail.
Thank you in advance for any ideas you come up with!
You have two options to make this compile.
Compile all the cpp files on one line
g++ main.cpp source.cpp -o main
Compile separately and link
g++ -c main.cpp
g++ -c source.cpp
g++ -o main main.o source.o
This is a bog-standard failure to bring in your source files, and has nothing to do with your compiler.
Henrys-MacBook-Pro-2:assignment1 HenryDashwood$ clang++ main.cpp
You didn't build & link source.cpp.
So, as far as Clang knows, the definition for clear() indeed does not exist.
Henrys-MacBook-Pro-2:assignment1 HenryDashwood$ clang++ main.cpp source.cpp

Error when trying to separating class into .h, .cpp

This is a minimal program that I made to understand this problem better.
ADT.h
#ifndef ADT_H
#define ADT_H
class ADT {
public:
void print();
};
#endif
ADT.cpp
#include <iostream>
#include "ADT.h"
using namespace std;
void ADT::print()
{
cout << "This program works." << endl;
}
testADT.cpp
#include <iostream>
#include "ADT.h"
using namespace std;
int main(void)
{
ADT sa;
sa.print();
return 0;
}
I compiled it with the vim/minGW compiler my school provided me like so:
g++ testADT.cpp
Which produced the following error:
C:\Users\King\AppData\Local\Tempcc6eoWAP.o:testADT.cpp(.text+0x15 reference to 'ADT::print()'
collect2.exe error: ld returned 1 exit status
Can you explain this error message and indicate the error in my code?
You didn't post the error, but I see that you're missing the semicolon after void print()in the header.
EDIT: That's a linker error. Each source file should be compiled into an object file; then the object files linked:
g++ -c -oADT.o ADT.cpp
g++ -c -otestADT.o testADT.cpp
g++ -oADT ADT.o testADT.o
You can also do it in one line as in michaeltang's answer, but then you can't recompile the sources individually (the 2 step method scales better).
You should also compile ADT.cpp
g++ -o testadt testADT.cpp ADT.cpp

Problem with using functions in 1 cpp file in another

I have 1 cpp file with main().
It relies on structs and functions in another (say, header.hpp).
The structs are defined in header.hpp, along with function prototypes. The functions are implemented in header.cpp.
When I try to compile, I get an error message saying:
undefined reference to `see_blah(my_thing *)`
So to give an overview:
header.hpp:
#ifndef HEADERDUR_HPP
#define HEADERDUR_HPP
struct my_thing{
int blah;
};
int see_blah(my_thing*);
#endif
header.cpp:
#include "header.hpp"
int see_blah(my_thing * thingy){
// ...
}
main.cpp:
#include <iostream>
#include "header.hpp"
using namespace std;
int main(void)
{
thinger.blah = 123;
cout << see_blah(&thinger) << endl;
return 0;
}
I have no idea what I'm doing wrong, and I can't find any answers. Thanks for any answers, they are very much appreciated!
You should be aware that you're missing a semi-colon at the end of your structure definition. This means it's folding the two (supposedly separate) parts together and that you're not getting the function prototype as a result.
The following compiles fine (after fixing a couple of other errors as well):
// main.cpp
#include <iostream>
#include "header.hpp"
using namespace std; // <- not best practice, but irrelevant here :-)
int main(void)
{
my_thing thinger; // <- need this!
thinger.blah = 123;
cout << see_blah(&thinger) << endl;
return 0;
}
// header.cpp
#include "header.hpp"
int see_blah(my_thing * thingy){
// ...
}
// header.hpp
#ifndef HEADERDUR_HPP
#define HEADERDUR_HPP
struct my_thing{
int blah;
}; // <- see here.
int see_blah(my_thing*);
#endif
with:
g++ -o progname main.cpp header.cpp
gcc actually gave an error with that code you posted so I'm not certain why your compiler didn't. That command line above is also important - if you're compiling and linking in one step, you need to provide all required C++ source files (otherwise the linker won't have access to everything).
Your code is fine. You're just compiling it wrong. Try:
g++ main.cpp header.cpp
You need to:
#include "header.hpp"
in your *main.cpp file.
If you have included header.hpp, than probably you haven't link it(header.cpp) with main.cpp. What environment are you using(g++ or VC++)?
Edit:for linking in g++ you must write:
g++ main.cpp header.cpp -o program
Also you are missing semicolon in the end of your struct!
thinger.blah = 123; should be along the lines of:
my_thing thinger = { 123 };
in addition to issues other posters have mentioned. please, update your example so it compiles.
You are missing a semi colon at the end of your structure definition and mixing it with the method.