Problem with using functions in 1 cpp file in another - c++

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.

Related

Preventing multiple definition in C++ [duplicate]

This question already has answers here:
multiple definition error c++
(2 answers)
Closed 1 year ago.
I am getting error:
/usr/bin/ld: /tmp/ccCbt8ru.o: in function `some_function()':
Thing.cpp:(.text+0x0): multiple definition of `some_function()'; /tmp/ccc0uW5u.o:main.cpp:(.text+0x0): first defined here
collect2: error: ld returned 1 exit status
when building a program like this:
main.cpp
#include "common.hpp"
#include "Thing.hpp"
int main() {
some_function();
}
common.hpp
#pragma once
#include <iostream>
void some_function() {
std::cout << "something" << std::endl;
}
Thing.hpp
#pragma once
class Thing {
public:
void do_something();
};
Thing.cpp
#include "Thing.hpp"
#include "common.hpp"
void Thing::do_something() {
some_function();
}
I'm compiling with: g++ main.cpp Thing.cpp -o main.out
I've also tried using include guards instead of #pragma once, but it didn't seem to work either. Is there something I am forgetting here?
#pragma once and include guards can only prevent multiple definitions in a single translation unit (a .cpp file). The individual units know nothing about each other, and so cannot possibly remove the multiple definition. This is why when the linker links the object files, it sees the multiple definitions still.
To solve this issue, change common.hpp to:
#pragma once
void some_function();
This tells the compiler that there is some code for some_function.
Then, add a file common.cpp that contains the code for the common.hpp header:
#include "common.hpp"
#include <iostream>
void some_function() {
std::cout << "something" << std::endl;
}
Finally, change the g++ command to:
g++ main.cpp common.cpp Thing.cpp -o main

C++ undefined reference to class (1 header 2 cpp's)

I am reading a book (C++ for dummies) as well as watching youtube videos to learn how to code. I am currently struggling with very simple class functions.
Main.cpp
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include "Test.h"
using namespace std;
int x;
int main(int nNumberofArgs, char* pszArgs[])
{
combat fight;
cout << x;
fight.dodmg();
cout << x;
return 0;
}
Test.h my header file with the class
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
using namespace std;
#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
class combat
{
public:
int dodmg();
void zero_out();
private:
int x;
};
#endif // TEST_H_INCLUDED
Test.cpp class functions
#include "Test.h"
int combat::dodmg()
{
x = x - 5;
return x;
}
void combat::zero_out()
{
x = 20
}
I tried to make this very simplistic just to figure out how to work a class.
I included a lot of #includes just to try and make sure it wasn't something stupid like I needed strings.
I am not sure why but the videos I watched simply had the header say
ifndef TEST_H (of their respective code, mine has an _INCLUDE as well, I tried deleting it and it still didn't work.
My unfortunate errors
on line 14 of main.cpp fight.dodmg(); it says
\Beginning_Programming-CPP\Playing_with_class\main.cpp|14|undefined reference to `combat::dodmg()'|
then below that
||error: ld returned 1 exit status|
How are you compiling this? I think this is an issue because you arent compiling your Test.cpp file. If you arent already, try compiling with the command:
g++ main.cpp Test.cpp -o MyProgram
UPDATE:
Few things, you dont have a closing statement to your #ifndef directive in Text.h, you will need a constructor to set the value of x so i added one to the combat class also you were missing a semicolon in the zero_out function. I added comments to all the lines I changed.
Okay try this:
Test.h
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
using namespace std;
#ifndef TEST_H_INCLUDED
#define TEST_H_INCLUDED
class combat
{
public:
combat(); // added constructor
int dodmg();
void zero_out();
private:
int x;
};
#endif // closed #ifndef
Text.cpp
#include "Test.h"
combat::combat() // implemented constructor
{
x = 20;
}
int combat::dodmg()
{
x = x - 5;
return x;
}
void combat::zero_out()
{
x = 20; // added ';'
}
Hope this helps,
Final edit: I dont think you really need your header guards in this scenario, you could remove the "#ifndef, #define, and the #endif" lines and not see a difference really
It sounds like you provide the wrong arguments for the compiler. Your header file (Test.h) simply provides signatures for the methods, but the implementations are given in the source file (Test.cpp).
This is an important part of writing C++ (or C) code. Your compiler does not automatically search for source files, so you need to tell it where to look, e.g.:
g++ -std=c++11 main.cpp Test.cpp -o main

How to properly include Header and Implementation Files?

I am a novice programmer in c++, and I am currently getting a compiling error
Undefined symbols for architecture x86_64
Supposedly this originates from how the header files and implementation files are included/coded.
Below is some code that generates the compiling error I am receiving
Main
//Main.cpp
#include <iostream>
#include <string>
#include "Animal.hpp"
using namespace std;
int main(){
Animal myPet;
myPet.shout();
return 0;
}
Header
//Animal.hpp
#ifndef H_Animal
#define H_Animal
using namespace std;
#include <string>
class Animal{
public:
Animal();
void shout();
private:
string roar;
};
#endif
Implementation
//Animal.cpp
#include "Animal.hpp"
#include <string>
Animal::Animal(){
roar = "...";
}
void Animal::shout(){
roar = "ROAR";
cout << roar;
}
This code generates my compiling issue. How would this issue be resolved?
Thanks for your time
EDIT
Undefined symbols for architecture x86_64:
"Animal::shout()", referenced from:
_main in test-5f7f84.o
"Animal::Animal()", referenced from:
_main in test-5f7f84.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
maybe you might want to see an alternative set of your 3 files, where things are a little more "sorted", you know, where things are put at places where they "really" belong to.
So here's the "new" header file ..
//Animal.hpp
#ifndef H_Animal
#define H_Animal
#include <string> // suffices
// Interface.
class Animal {
std::string roar; // private
public:
Animal();
void shout();
};
#endif
then the source file ..
//Animal.cpp
#include "Animal.hpp"
#include <iostream> // suffices
// Constructor.
Animal::Animal()
:
roar("...") // data member initializer
{}
// Member function.
void Animal::shout() {
roar = "ROAR";
std::cout << roar;
}
and the main program ..
//Main.cpp
#include "Animal.hpp"
int main(){
Animal thePet;
thePet.shout(); // outputs: `ROAR'
}
plus a little GNU makefile ..
all: default run
default: Animal.cpp Main.cpp
g++ -o Main.exe Animal.cpp Main.cpp
run:
./Main.exe
clean:
$(RM) *.o *.exe
Kick-off things typing just "make" in your cmd-line. Did you like it? --
Regards, M.
I can only find one error in your code and your compiler should have told you that one.
In Animal.cpp, you are using std::cout but you're not #includeing <iostream>. You #include it in Main.cpp but it is not needed there.
If you (really) want to refer to std::cout as cout in Animal.cpp, you also have to add a using namespace std directive in that file.
The using directive in the header file (Animal.hpp) is evil. Get rid of it and type std::string instead. Putting using directives into headers litters the namespaces of all files that use it.
I also don't understand your intentions with the roar member. What is the point of assigning "..." to it in the constructor and re-assigning "ROAR" to it every time shout is called? Couldn't you do without that variable and simply have
void
Animal::shout()
{
std::cout << "ROAR\n";
}
? I have added a newline because you'd probably want one.
The main issue I was having with this coding project was solved by #JamesMoore.
"#Nicholas Hayden Okay if you have three files, test.cpp(which has main), animal.cpp, and animal.hpp. The command should be g++ animal.cpp test.cpp. You need to compile all source files."
I am currently not using an IDE. So, when I was calling the compiler to compile my main.cpp - It was an issue of compiling the implementation file.
g++ test.cpp
needed to become
g++ test.cpp animal.cpp
This would call the compiler to compile everything the program needed.

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

How to use header files?

I wanted to learn using header files. and I got an error. here is my code:
printmyname.h:
void printMyName();
printmyname.cpp:
#include "printmyname.h"
void printMyName() {
cout << "omer";
}
try.cpp (main file):
#include <iostream>
#include "printmyname.h"
using namespace std;
int main() {
printMyName();
return 0;
}
Here is the error:
undefined reference to `printMyName()`
What's is the problem?
Undefine reference has nothing to do with your header file in this case. It means the linker cannot find the implementation of printMyName which is in printmyname.cpp. If you are using g++, you should try:
g++ try.cpp printmyname.cpp -o yourBinaryName
If you are using a makefile, you should add dependency(printmyname.cpp) correctly for try.cpp.
Edit:
As #zmo suggest in his comment:
you can also do it through a two times compilation (more suitable with Makefiles):
g++ -c printmyname.cpp
g++ try.cpp printmyname.o -o yourBinaryName
If you are using Windows, you need to add the printmyname.cpp to your project too.
Consider adding an include guard to your header
#ifndef PRINTMYNAME_INCLUDED
#define PRINTMYNAME_INCLUDED
void printMyName();
#endif
You will also need to move the #include <iostream> and using namespace std; from the try.cpp to the printmyname.cpp file.
You need to add code/definition in printMyName.cpp inside printMyName.h only.
void printMyName();
{
cout << "omer";
}