I'm writing a program that calculates the norm of a vector (dot product with itself).
I have no problem implementing the code, what I can't do is call a function from a function other than the main one.
header.h
#ifndef HEADER
#define HEADER
void readArray(double [], int &);
void printArray(double [], int &);
void norm(double [], int &);
double scalarProduct(double [], int &);
#endif
norm.cc
// norm.cc
#include <iostream>
#include <cmath>
using namespace std;
void norm(double array[], int & size)
{
double norm;
norm = sqrt(scalarProduct(array, size));
cout << "Norm = " << norm << endl;
}
scalarProduct.cc
// scalarProduct.cc
#include <cmath>
double scalarProduct(double array[], int & size)
{
double ps = 0.0;
for(int i = 0; i < size; i++)
{
ps += pow(array[i], 2);
}
}
in the main.cc file I added the line
#include "header.h"
and all the functions I call from main work like a charm, but calling productScalar() from norm() doesn't work. I added the same #include "header.h" line but the compiler says I can't define the same function more than once. How can I solve this?
Add
#include "header.h"
into norm.cc
Related
I am a beginner and running into the above-said error. The following is the complete code from three files:
ball.h:
#ifndef BALL_H
#define BALL_H
namespace
{
inline constexpr double gravity{ 9.81 };
}
double getInitialHeight(void);
double calculateHeight(double, int);
void printHeight(double, int);
void calculateAndPrintHeight(double, int);
void solve(void);
#endif
ball.cpp:
#include "ball.h"
#include <iostream>
double getInitialHeight()
{
std::cout << "Enter the height of the tower in meters ";
double initialHeight{};
std::cin >> initialHeight;
return initialHeight;
}
double calculateHeight(double initialHeight, int secondsPassed)
{
double distanceFallen{ BALL_H::gravity * secondsPassed * secondsPassed / 2.0 };
double currentHeight{ initialHeight - distanceFallen };
return currentHeight;
}
void printHeight(double height, int secondsPassed)
{
if (height > 0.0)
{
std::cout << "At " << secondsPassed << " seconds, the ball is at height\t" << height << " meters.\n";
}
else
{
std::cout << "At " << secondsPassed << " seconds, the ball is on the ground.\n";
std::exit(0);
}
}
void calculateAndPrintHeight(double initialHeight, int secondsPassed)
{
double height{ calculateHeight(initialHeight, secondsPassed) };
printHeight(height, secondsPassed);
}
void solve()
{
const double initialHeight{ getInitialHeight() };
int secondsPassed{ 0 };
while (true)
{
calculateAndPrintHeight(initialHeight, secondsPassed);
secondsPassed++;
}
}
Solution.cpp(the main project file in the solution):
#include <iostream>
#include "ball.h"
int main()
{
solve();
return 0;
}
I understand that this problem is caused because linker cannot find a reference to solve(). However, I am not sure how to solve the issue. One easy solution is to simply include ball.cpp rather than ball.h:
#include <iostream>
#include "ball.cpp"
int main()
{
solve();
return 0;
}
This code works but I'd like to know how to use headers instead since I am not sure if this a good practice.
EDIT:
Here's the error list:
When you add header file, you could right click Header Files and select Add->New Item.
When you add .cpp file, you could right click Source Files and select Add->New Item.
Then, add the following code in Source.cpp.
#include <iostream>
#include "ball.h"
int main()
{
solve();
return 0;
}
Finally, it works fine.
I am a novice at C++. I have started writing a rather large code on a project and I want to make a good base for that. I get the following error when running in Visual Studio:
Exception thrown: read access violation. this was nullptr. occurred
After searching similar questions, I could not find the solution for my code. The error is occurring in Driver.cpp at:
m_setup->SetEquation(...)
Any help is really appreciated. I also appreciate if you have suggestion to improve my code structure.
Main.h:
#ifndef FEM_AD1D_MAIN_H
#define FEM_AD1D_MAIN_H
namespace FEM_AD1D
{
class Driver;
Driver* m_driver;
}
#endif
Main.cpp:
#include "Main.h"
#include "Driver.h"
#include <iostream>
using namespace FEM_AD1D;
int main()
{
std::cout << "Hello World!\n";
m_driver->Run();
}
Driver.h:
#ifndef FEM_AD1D_DRIVER_H
#define FEM_AD1D_DRIVER_H
namespace FEM_AD1D
{
class Setup;
class Driver
{
public:
Driver(Setup* setup);
void Run();
void PreProc();
private:
Setup* m_setup;
const int m_nDim = 1;
const double m_aCoef = 1.0;
const double m_bCoef = 3.0;
const double m_cCoef = 0.0;
const double m_fCoef = 1.0;
const double m_xMin = 0.0;
const double m_xMax = 1.0;
const int m_nElem = 5;
const int m_elemType = 2;
const double m_meshStretch = 0.0;
const int m_nGaussPoint = 3;
};
}
#endif
Driver.cpp:
#include "Driver.h"
#include "Setup.h"
#include <iostream>
#include <array>
using namespace FEM_AD1D;
Driver::Driver(Setup* setup)
{
m_setup = setup;
//m_setup = new Setup();
}
void Driver::Run()
{
PreProc();
}
void Driver::PreProc()
{
std::cout << "Hello World 2!\n";
m_setup->SetEquation(m_nDim, m_aCoef, m_bCoef, m_cCoef, m_fCoef);
}
Setup.h:
#ifndef FEM_AD1D_SETUP_H
#define FEM_AD1D_SETUP_H
#include <vector>
namespace FEM_AD1D
{
class Setup
{
public:
Setup();
void SetEquation(int nDim, double aCoef, double bCoef, double cCoef, double fCoef);
private:
int m_nDim;
double m_aCoef;
double m_bCoef;
double m_cCoef;
double m_fCoef;
};
}
#endif
Setup.cpp:
#include "Setup.h"
#include "Driver.h"
#include <iostream>
#include <vector>
using namespace FEM_AD1D;
Setup::Setup() :
m_nDim(0),
m_aCoef(0.0),
m_bCoef(0.0),
m_cCoef(0.0),
m_fCoef(0.0)
{
}
void Setup::SetEquation(int nDim, double aCoef, double bCoef, double cCoef, double fCoef)
{
// Set the coefficients of the equation
std::cout << "Hello World 3!\n";
m_nDim = nDim;
m_aCoef = aCoef;
m_bCoef = bCoef;
m_cCoef = cCoef;
m_fCoef = fCoef;
}
I have a problem. In my Qt project I'm having an error. Tt says:
multiple definition of estructura
I think it is because I'm using too many "#includes", but I don't know how to fix it.
This is my program:
Struct.h
#ifndef STRUCT_H
#define STRUCT_H
#include <stdio.h>
#include <string>
struct Circulo{
std::string nombre;
int capacidad;
int statusMujer[4];
int hijos[4];
};
struct Circulo estructura[30];
#endif // STRUCT_H
Logica.h
#ifndef LOGICA_H
#define LOGICA_H
#include <iostream>
void madresStatusCodificados(std::string , int , int[]);
void ListadoDeCirculos(int, int , std::string []);
std::string CirculoMayorCapacidad(int );
int NinnosEnCirculosconStatus(int , int );
void Listado(int);
#endif // LOGICA_H
interfaz.cpp
#include <Interfaz/Interfaz.h>
#include <Logica/Defecto.h>
#include <Interfaz/Menu.h>
#include <Logica/Struct.h>
#include <iostream>
using namespace std;
void Principal(){
cin>>estructura[i].statusMujer[3];
cout<<"Escriba la cantidad de hijos con madres desconocidas"<<endl;
cin>>estructura[i].hijos[3];
i++;
}else{
break;
}
}
}
Logica.cpp
#include <iostream>
using namespace std;
//#include <Logica/Logica.h>
#include <Logica/Struct.h>
void madresStatusCodificados(string t, int h , int k[]){
for(int i=0;i<h;i++){
if(estructura[i].nombre==t){
k[0]=estructura[i].statusMujer[0];
k[1]=estructura[i].statusMujer[1];
k[2]=estructura[i].statusMujer[2];
k[3]=estructura[i].statusMujer[3];
}
}
}
void ListadoDeCirculos(int g,int u,string h[]){
for(int i=0;i<u;i++){
if(estructura[i].statusMujer[g-1]!=0)
h[i]=estructura[i].nombre;
}
}
string CirculoMayorCapacidad(int k){
int n=-1;
string l;
for(int i=0;i<k;i++){
if(estructura[i].capacidad>n){
n=estructura[i].capacidad;
l=estructura[i].nombre;
}
}
return l;
}
int NinnosEnCirculosconStatus(int a,int b){
int h=0;
for(int i=0;i<b;i++){
h=h+estructura[i].hijos[a-1];
}
return h;
}
void Listado(int y){
for(int i=0;i<y;i++){
cout<<"NOMBRE DEL CIRCULO CAPACIDAD Madres solteras Madres trabajadoras Madres caso social Madres desconocidas "<<endl;
cout<<estructura[i].nombre<<""<<estructura[i].capacidad<<estructura[i].statusMujer[0]<<estructura[i].statusMujer[1]<<estructura[i].statusMujer[2]<<estructura[i].statusMujer[3]<<endl;
}
}
I am getting this error:
Errors
You have defined a variable named "estructura" in several files, the error tells you that it was first defined in Struct.h being called #included in Logica.cpp,
struct Circulo estructura[30];
you have another definition the the file Defecto.h or a file included by Defecto.h
Move the definition of estructura in a cpp file of your choice, then declare it as extern wherever you need it. And you can omit the struct keyword, in c++.
In a struct.cpp file:
#include "Struct.h"
Circulo estructura[30];
In your Logica.cpp and Interfaz.cpp files:
#include "Struct.h"
extern Circulo estructura[30];
Here is a long and detailed explanation of your issue.
Hi I am working on a program that involves a Main.cpp, Connect4.cpp, and Connect4.h file. When I compile my program I am getting an error in the Main file saying that my playGame function is an undefined reference. I am compiling both files together(main first) I believe something is wrong in the way I am trying to dynamically call the function playGame. Any input would be much appreciated!
Main.cpp
#include <iostream>
#include <array>
#include "Connect4.h"
void playGame();
using namespace std;
int main()
{
Connect4 *ptr;
ptr=new Connect4;
ptr-> playGame();
delete ptr;
}
Connect4.cpp
#include <iostream>
#include <array>
#include "Connect4.h"
char gameBoard[9][7];
int rows;
int columns;
using namespace std;
void playGame()
{
void display();
int selectColumn(bool);
int tokenPlacement(char token, int columns);
bool winOrLose();
cout<<"Welcome to Connect Four.";
for(int i=0; i<rows;++i)
{
for(int j=0; j<columns; ++j)
{
gameBoard[i][j]=' ';
}
}
bool player1Turn=true;
char winner='n';
int column =0;
while(true){
display();
column=selectColumn(player1Turn);
if(player1Turn==true)
{
tokenPlacement('x',column);
player1Turn=false;
}
else
{
tokenPlacement('o', column);
player1Turn=true;
winner= winOrLose();
if(winner!='n')
{
break;
}
}
cout<<"Winner is:"<<winner;
}
Connect4.h
#ifndef CONNECT4_H_
#define CONNECT4_H_
#include
using namespace std;
class Connect4 {
public:
static void playGame();
private:
void display();
int selectColumn(bool);
int tokenPlacement(char, int);
bool winOrLose();
char gameBoard[9][7];
};
#endif /* CONNECT4_H_ */
Im receiving this error when trying to compile my code.
$ g++ -o BangBangControlTest BangBangControl.o BangBangControlTest.o
ld: duplicate symbol _heating_unit in BangBangControlTest.o and BangBangControl.o for architecture x86_64
collect2: ld returned 1 exit status
I am new to C++ and can't find out what is wrong. I've searched through many tutorials and looked at similar error messages received by other stack users. Here are my classes.
"BangBangControlTest.cpp"
// Test function
#include <iostream>
#include "BangBangControl.h"
using namespace std;
int main(){
BangBangControl control(50, true, 75);
for(int i = 0; i < 50; i++){
std::cout << "Temp = " << control.update() << endl;
}
return 0;
}
"BangBangControl.cpp"
#include <iostream>
#include "BangBangControl.h"
using namespace std;
BangBangControl::BangBangControl(int temp, bool isOn, int initialTemp){
heating_unit = HeatingUnit(isOn, initialTemp);
temp_to_maintain = temp;
}
void BangBangControl::setTemp(int temp){temp_to_maintain = temp;}
int BangBangControl::getTemp(){return temp_to_maintain;}
int BangBangControl::update(){
int b=heating_unit.tick();
if (b > temp_to_maintain + 2) heating_unit.turnOff(); if (b < temp_to_maintain - 2) heating_unit.turnOn();
return b;
}
"BangBangControl.h"
// BangBangControl header
#include <iostream>
#include "HeatingUnit.h"
using namespace std;
HeatingUnit heating_unit;
int temp_to_maintain;
class BangBangControl{
public:
BangBangControl(int, bool, int);
void setTemp(int);
int getTemp();
int update();
};
"HeatingUnit.cpp"
// HeatingUnit class implementation
#include <iostream>
#include "HeatingUnit.h"
using namespace std;
HeatingUnit::HeatingUnit(bool a, int b){
isOn = a;
temp = b;
}
void HeatingUnit::turnOn(){isOn = true;}
void HeatingUnit::turnOff(){isOn = false;}
int HeatingUnit::tick(){
if(isOn && temp <= 100){
return ++temp;
}
else if((!isOn) && temp >= 0){
return --temp;
}
else{
return temp;
}
}
"HeatingUnit.h"
#include <iostream>
using namespace std;
class HeatingUnit{
public:
bool isOn;
int temp;
HeatingUnit();
HeatingUnit(bool, int);
void turnOn();
void turnOff();
int tick();
};
You see that HeatingUnit heating_unit; in your header file? You need to put extern in front of it, and copy the original version without the extern to the .cpp file, optionally specifying an initial value there.
You can read more about this here: How do I use extern to share variables between source files?