Codeblocks c++ undefined reference error, class is defined - c++

Hey guys I asked a question the other day about some c++ code that I couldn't get to work. I took everyones advice as to how to create objects in c++ but now I get undefined reference errors. I am using the latest code blocks version and using that to compile. I have read that this is caused by not linking some files during compilation, and that it means I have defined the class in the header file but not in the code, which confuses me because from my understanding (a profs example) I am declaring the objects.
Header File
MathObject.h
class MathObject{
private:
int num1;
int num2;
public:
int sum();
MathObject(int n, int m);
};
MathObject file
MathObject.cpp
#include <iostream>
#include "MathObject.h"
using namespace std;
MathObject :: MathObject(int n, int m){
num1 = n;
num2 = m;
}
int MathObject :: sum(){
return num1+num2;
}
Main File
#include <iostream>
#include "MathObject.h"
using namespace std;
int main(int args, char *argv[]){
MathObject *mo = new MathObject(3,4);
int sum = mo -> sum();
MathObject mo2(3,4);
//cout << sum << endl;
return 0;
}
The undefined reference is for all calls to anything in the MathObject class, I have been searching for a small c++ example that I can understand. (The syntax is so different from java)
This used to happen when I tried to use multiple files in c, could this be an issue with my computer?

In the "Projects" tab in codeblocks, right-click your project's name and select "Add Files..."
Alternately, you can choose "Add files..." from "Project" in the application's main menu.
Use this to add all of your source files to your project.
Currently MathObject.cpp is missing from that list, so it's not getting compiled or linked.

g++ MathObject.cpp main.cpp -o main

Found a solution from code::blocks forum:
-Project -> "Build Options
-Make sure the correct target is highlighted on the left side; if you do not know select the project, top one.
-Select Tab "Search Directories"
-Select Sub-Tab "Compiler"
-"Add" the path to the folder that contains the header. Single Folder per line.
Just add your current folder or location of your header file to the path.
Link: http://forums.codeblocks.org/index.php?topic=14713.0

You can do this simply by adding .cpp file of the class in main.cpp.
#include <iostream>
#include "MathObject.h"
#include "MathObject.cpp"
using namespace std;
int main(int args, char *argv[]){
MathObject *mo = new MathObject(3,4);
int sum = mo -> sum();
MathObject mo2(3,4);
//cout << sum << endl;
return 0;
}

To fix undefined reference error :-
Settings -> compiler... -> Build options
finally mark "Explicitly add currently compiling file's directory to compiler search dirs"

I try this and works fine!
MAIN.cpp
#include <iostream>
#include "MathObject.h"
using namespace std;
int main(int args, char *argv[]){
MathObject *mo = new MathObject(3,4);
int sum = mo->sum();
MathObject mo2(3,4);
int sum2 = mo2.sum();
cout << sum << endl;
cout << sum2 << endl;
system("pause");
return 0;
}
MathObject.h
class MathObject
{
private:
int num1;
int num2;
public:
MathObject(void);
~MathObject(void);
int sum();
MathObject(int n, int m);
};
MathObject.cpp
#include "MathObject.h"
MathObject::MathObject(void)
{
}
MathObject::~MathObject(void)
{
}
int MathObject::sum(){
return num1+num2;
}
MathObject::MathObject(int n, int m){
num1 = n;
num2 = m;
}
Compile with:
g++ MathObject.cpp main.cpp -o main.exe

Related

How do I resolve this error: expected unqualified-id before '-' token

Context: Preparing for the Fall semester, I whipped up a quick code file to check if you can call a function as a parameter of another function. However, before I could compile the code and check - this error happened.
C:\mingw64\bin\g++.exe -fdiagnostics-color=always -g
\wsl$\kali-linux\home\tyrael\Foundry\morga.cpp -o
\wsl$\kali-linux\home\tyrael\Foundry\morga.exe
'\wsl$\kali-linux\home\tyrael\Foundry'
CMD.EXE was started with the above path as the current directory.
UNC paths are not supported. Defaulting to Windows directory.
In file included from
C:/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/iostream:39,
from \wsl$\kali-linux\home\tyrael\Foundry\morga.cpp:1:
C:/mingw64/lib/gcc/x86_64-w64-mingw32/8.1.0/include/c++/ostream:681:49:
error: expected unqualified-id before '-' token
__rvalue_ostream_type<_Ostream>>::type - operator<<(_Ostream&& __os, const _Tp& __x)
^
Build finished with error(s).
The terminal process failed to launch (exit code: -1).
Terminal will be reused by tasks, press any key to close it.
I had tried moving around the #include statement, didn't work.
I tried to isolate the cause of the error by commenting out huge swaths of the code, but the error still there.
My only guess as far as what the issue could be is that the compiler is very angy that I am trying to call a function as a parameter for another function, but I can't verify that.
I'm truly at a loss, I just don't know what it could be. Any help would be much appreciated!
This is the code:
#include <iostream>
using std::cout;
int combiner();
int multiplier(int target_sum);
// Forward declaration of my functions
int combiner() {
int input1 = 5;
int input2 = 10;
int input3 = 15;
int sum = input1 + input2 + input3;
return sum;
}
// simple function that takes numbers and combines them into one total sum
int multiplier (int target_sum) {
int big_sum = target_sum * 5;
return big_sum;
}
// simple function that takes a number and multiples by 5
int main (int argc, char** argv) {
combiner();
int final = multiplier(combiner());
cout << "This is our final number: " << final;
return 0;
}
// putting it all together, using a function as a parameter for another function
I remembered that you can't pass a func as a parameter for another func in C, but you can in other langs. However, even when I get rid of that process - I still hit the error. Here's the new code:
#include <iostream>
using std::cout;
int combiner();
int multiplier(int target_sum);
int combiner() {
int input1 = 5;
int input2 = 10;
int input3 = 15;
int sum = input1 + input2 + input3;
return sum;
}
int multiplier (int target_sum) {
int big_sum = target_sum * 5;
return big_sum;
}
int main (int argc, char** argv) {
int tiago = combiner();
int final = multiplier(tiago);
// Storing return value of combiner() into a int variable, using that var as
// parameter instead for 2nd function - multiplier
cout << "This is our final number: " << final;
return 0;
}
EDIT: In the vein of investigating my compiler, here are some screenshots to show what my compilation process looks like on VS Code.
Selecting the compiler type
Select the actual compiler, the one I want is g++

C++ "undefined reference" error when working with custom header file [duplicate]

This question already has answers here:
What is an undefined reference/unresolved external symbol error and how do I fix it?
(39 answers)
Closed 2 years ago.
I am working with my own custom header file for the first time in C++. The goal of this program is to create a dice class that can be used to create an object oriented dice game.
When I go to run my program (made of three files (header/class specification file, class implementation file, and finally the application file), I am getting an error:
undefined reference to `Die::Die(int)'
I have about six of these errors when running app.cpp, one for every time I try to access information from my Die class.
Full Error Message
My Three Files
Die.h
#ifndef DIE_H
#define DIE_H
#include <ctime>
//#include
class Die
{
private:
int numberOfSides=0;
int value=0;
public:
Die(int=6);
void setSide(int);
void roll();
int getSides();
int getValue();
};
#endif
Die.cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include "Die.h"
using namespace std;
Die::Die(int numSides)
{
// Get the system time.
unsigned seed = time(0);
// Seed the random number generator.
srand(seed);
// Set the number of sides.
numberOfSides = numSides;
// Perform an initial roll.
roll();
}
void Die::setSide(int side=6){
if (side > 0){
numberOfSides = side;
}
else{
cout << "Invalid amount of sides\n";
exit(EXIT_FAILURE);
}
}
void Die::roll(){
const int MIN_VALUE = 1; // Minimum die value
value = (rand() % (numberOfSides - MIN_VALUE + 1)) + MIN_VALUE;
}
int Die::getSides()
{
return numberOfSides;
}
int Die::getValue()
{
return value;
}
app.cpp
#include <iostream>
#include "Die.h"
using namespace std;
bool getChoice();
void playGame(Die,Die,int &, int &);
int main()
{
int playerTotal=0;
int compTotal=0;
Die player(6);
Die computer(6);
while(getChoice()){
playGame(player, computer, playerTotal, compTotal);
getChoice();
}
}
void playGame(Die play, Die comp, int &pTotal, int &cTotal){
//add points
play.roll();
pTotal += play.getValue();
comp.roll();
cTotal += comp.getValue();
//show points each round
cout << "You have " << pTotal << " points;\n";
}
bool getChoice(){
bool choice;
cout << "Would you like to roll the dice? (Y/N): ";
cin>> choice;
return choice;
}
You should compile both app.cpp and Die.cpp at the same time:
g++ app.cpp Die.cpp

gdb doesn't stop in a line with #include directive

The problem is that, when I set a breakpoint at the line of the #include, gdb just ignore the line and stop at the next instruction in the main (I compiled the main.cpp with g++ -g -O2 -std=c++11).
The program works perfect (-O2 doesn't affect the result at all), but I want to check what exactly does something inside that file, but I can't because gdb doesn't let me enter the code inside the file.
How can I debug code inside other file? Is it even possible?
Edit: Here is the code
main.cpp
#include <iostream>
#include <cstdlib>
#include <chrono>
#include "inc/includes.h"
template <class T>
void PrintVector(T* vector, int size){
for (int i=0; i<size; ++i){
std::cout << vector[i] << " ";
}
std::cout << std::endl;
}
template <class T>
void CheckTime(void (*f)(T*&, int), T* &vector, int size){
std::chrono::high_resolution_clock::time_point tantes, tdespues;
std::chrono::duration<double> transcurrido;
tantes = std::chrono::high_resolution_clock::now();
(*f)(vector, size);
tdespues = std::chrono::high_resolution_clock::now();
transcurrido = std::chrono::duration_cast<std::chrono::duration<double>(tdespues - tantes);
std::cout << size << " " << transcurrido.count() << std::endl;
}
int main(int argc, char * argv[]){
if (argc != 2){
std::cerr << "Formato " << argv[0] << " <num_elem>" << std::endl;
return -1;
}
int n = atoi(argv[1]);
int range;
#if defined RADIXSORTLSD || defined RADIXSORTMSD
unsigned short * array = new unsigned short[n];
range = (n<65536)?n:65536;
#else
unsigned int * array = new unsigned int[n];
range = n;
#endif
srand(time(0));
for (int i = 0; i < n; i++){
array[i] = rand()%range;
}
#ifdef PRINT
PrintVector(array, n);
#endif
#include "inc/select.h" //Here is the problem for debugging
#ifdef PRINT
PrintVector(array, n);
#endif
}
includes.h
#include "../src/radixsortlsd.cpp"
#include "../src/radixsortmsd.cpp"
#include "../src/mergesort.cpp"
#include "../src/bitonicsort.cpp"
#include "../src/insertion.cpp"
#include "../src/slowsort.cpp"
#include "../src/selection.cpp"
select.h This is the code I want to debug. I decided to separate it from the main because it will grow a lot.
// The calls to CheckTime takes the first parameter as the direction to a function, previously defined inside the cpps of includes.h
#ifdef RADIXSORTLSD
CheckTime(&RadixSortLSD, array, n);
#endif
#ifdef RADIXSORTMSD
CheckTime(&RadixSortMSD, array, n);
#endif
#ifdef MERGESORT
CheckTime(&MergeSort, array, n);
#endif
#ifdef INSERTION
CheckTime(&Insertion, array, n);
#endif
#ifdef SLOWSORT
CheckTime(&SlowSort, array, n);
#endif
#ifdef SELECTION
CheckTime(&Selection, array, n);
#endif
#ifdef BITONICSORT
CheckTime(&BitonicSort, array, n);
#endif
I hope this help. Note that everything compiles great and works great (I made sure that the macros I defined when compiling are the correct ones)
Note: By debugging (not the right word) I meant checking how a function works (a function I don't fully understand).
Possibly you could break at MyFunction(), then run 'bt' command to see the stack. Then you see, is there any additional stack frame or what stack frames consist of in terms of source files, it might help
First of all:
A include is a preprocessor directive which never generates code. Debuggers can stop only on things which can be executed. Including a file works during compilation, not during runtime.
The next:
Your included files will define some values, functions, classes and a lot other. So you must give the debugger an idea where to stop.
And at all:
Including 'cpp' files is really trash! There are only very seldom reasons to do this.
But ok, how to proceed:
If your header file ( or included cpp file ) provides a function, you simply can do a break Func and run your program. No need to open any file in a gui for gdb before.
If you want to look inside the included files, you also can list myheader.h:1. The 1 one is the line of code you want to start looking into the file.
And a hint: Please provide much smaller code examples which persons can compile for themselves to give you more detailed help. You example is really bad to understand!
Example session:
Header: f.h
#include <stdlib.h>
void g(void)
{
malloc(4000);
}
void f(void)
{
malloc(2000);
}
main.cpp:
#include "f.h"
int main(void)
{
int i;
int* a[10];
for (i = 0; i < 10; i++) {
a[i] = (int*)malloc(1000);
}
f();
g();
for (i = 0; i < 10; i++) {
free(a[i]);
return 0;
}
}
Example session:
> gdb prog
gdb) break f
Breakpoint 1 at 0x40061a: file main.cpp, line 10.
(gdb) run
Starting program: /home/xxx/go
Breakpoint 1, f () at f.h:10
10 malloc(2000);
(gdb) list
5 malloc(4000);
6 }
7
gdb )
Now you can walk through your subroutine with step.

C++ Object reference not set to an instance of an object

When I try to compile the following program it says "Build failed. Object reference not set to an instance of an object" . I'm kinda new to c++ so if anybody can help me it'll be great . I'm just trying out some example I saw in a book so I don't know whats wrong with this .
using namespace std;
class matrix
{
int m[3][3];
public:
void read(void);
void display(void);
friend matrix trans(matrix);
}
void matrix :: read(void)
{
cout<<"Enter the elements of the 3x3 array matrix : \n";
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
cout<<"m["<<i<<"]["<<j<<"] =";
cin>>m[i][j];
}
}
}
void matrix :: display(void)
{
int i,j;
for(i=0;i<3;i++)
{
cout<<"\n";
for(j=0;j<3;j++)
{
cout<<m[i][j]<<"\t";
}
}
}
matrix trans(matrix m1)
{
matrix m2;
int i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
m2.m[i][j] = m1.m[j][i];
}
}
return(m2); //returning an object
}
int main()
{
matrix mat1,mat2;
mat1.read();
cout<<"\nYou entered the following matrix :";
mat1.display();
mat2 = trans(mat1);
cout<<"\nTransposed matrix :";
mat2.display();
getch();
return 0;
}
1 - Insert semi-colon after the class definition
2 - Insert the correct headers
#include <iostream>
#include <conio.h>
3 - Try getting a compiler that is a bit more descriptive with regards to errors. I did all that i mentioned and your program ran. Try it
It compiles fine after you fix your missing semi-colon (after your class declaration) and add either #include <conio.h> (Visual Studio) or #include <curses.h> (for a POSIX system) for the getch() function (which is not a standard function).

BigInteger java method to gmp c++

I want to convert java code in c++
code is
BigInteger value = new BigInteger(125, RandomNumber);
BigInteger clone = new BigInteger(value.toByteArray());
How to write this code in cpp using gmp library?
Please anyone help me.
Thanks.
With C++ you can do that
#include <gmpxx.h>
#include <gmp.h>
#include <iostream>
using namespace std;
int main(){
mpz_class value;
mpz_class clone;
gmp_randclass r(gmp_randinit_default);
value = r.get_z_bits(125);
clone = value;
cout << value << endl;
cout << clone << endl;
return 0;
}
and compile with
g++ file.cpp -lgmpxx -lgmp
to install libgmpxx.a
put --enable-cxx to the build option of ./configure
here is a carbon copy from wikipedia
Here is an example of C code showing the use of the GMP library to multiply and print large numbers:
#include <stdio.h>
#include <stdlib.h>
#include <gmp.h>
int main(void)
{
mpz_t x;
mpz_t y;
mpz_t result;
mpz_init(x);
mpz_init(y);
mpz_init(result);
mpz_set_str(x, "7612058254738945", 10);
mpz_set_str(y, "9263591128439081", 10);
mpz_mul(result, x, y);
gmp_printf("\n %Zd\n*\n %Zd\n--------------------\n%Zd\n\n", x, y, result);
/* free used memory */
mpz_clear(x);
mpz_clear(y);
mpz_clear(result);
return EXIT_SUCCESS;
}
This code calculates the value of 7612058254738945 × 9263591128439081.
Compiling and running this program gives this result. (The -lgmp flag is used if compiling on Unix-type systems.)
7612058254738945
*
9263591128439081
--------------------
70514995317761165008628990709545