I'm facing a problem using forward declaration, and I don't know how to fix it. Here's my files:
BubblePlug.h
#ifndef _BUBBLEPLUG_
#define _BUBBLEPLUG_
#include "IPlug_include_in_plug_hdr.h"
#include "resource.h"
#include "IControl.h"
class IPianoRoll;
class IMidiEngine;
class BubblePlug: public IPlug
{
private:
public:
IMidiEngine *pMidiEngine;
IPianoRoll *pPianoRoll;
BubblePlug(IPlugInstanceInfo instanceInfo);
~BubblePlug();
};
#endif // !_BUBBLEPLUG_
BubblePlug.cpp
#include "BubblePlug.h"
#include "IPlug_include_in_plug_src.h"
#include "IPianoRoll.h"
#include "IMidiEngine.h"
BubblePlug::BubblePlug(IPlugInstanceInfo instanceInfo) : IPLUG_CTOR(10, 1, instanceInfo) {
pPianoRoll = new IPianoRoll(this, 8, 8);
pMidiEngine = new IMidiEngine(this);
}
BubblePlug::~BubblePlug() {
delete pPianoRoll;
delete pMidiEngine;
}
IPianoRoll.h
#ifndef _IPIANOROLL_
#define _IPIANOROLL_
#include "IMidiEngine.h"
class IPianoRoll : public IControl
{
private:
BubblePlug *pBubblePlug;
public:
IPianoRoll(BubblePlug *bubbleplug, int x, int y) : IControl(bubbleplug, IRECT(x, y, x + 10, y + 10)), pBubblePlug(bubbleplug) {
}
~IPianoRoll() {
};
bool Draw(IGraphics *pGraphics) {
return true;
}
void Random(bool onlyScore = false) {
pBubblePlug->pMidiEngine->Init();
}
void Start() {
}
};
#endif // !_IPIANOROLL_
IMidiEngine.h
#ifndef _IMIDIENGINE_
#define _IMIDIENGINE_
class IMidiEngine
{
private:
BubblePlug *pBubblePlug;
public:
IMidiEngine(BubblePlug *bubbleplug) : pBubblePlug(bubbleplug) {
}
~IMidiEngine() {
};
void Init(bool randomScore = true) {
pSamplwhk->pPianoRoll->Start();
}
};
#endif // !_IMIDIENGINE_
when I compile, it says around pSamplwhk->pPianoRoll->Start();:
use of undefined type 'IPianoRoll'
left of '->Start' must point to class/struct/union/generic type
VS2015 find each element writing the code (I've no problem), it happens only when I compile (Build).
Why? I pass BubblePlug and I do forward of both IPianoRoll and IMidiEngine, including them in order (on BubblePlug.cpp).
IMidiEngine should know everythings about IPianoRoll (which it is included first).
At least, I should have problem at "runtime", why at compile?
Can you help me to understand the problem and how to fix it? Thanks.
IPianoRoll.h includes IMidiEngine.h, so no matter in which order you include the two files, the definition of IPianoRoll will always come after the init function where it is being used.
One way to avoid this is to move the body of the init function into a separate .cpp file:
In IMidiEngine.h:
void Init(bool randomScore=true);
In IMidiEngine.cpp:
void IMidiEngine::Init(bool randomScore) {
pSamplwhk->pPianoRoll->Start();
}
Related
There are 1 main class and 3 classes: Main, MLME, MAC and Network.
I would want an MLME object to be created within the MAC object upon calling the constructor of the MAC. Then share the same object to the Network object when calling the Network constructor.
This without making the MLME object global or allocating memory with malloc() or new.
I believe this should be done with references which I don't understand fully. Also there might have to be some initializer-list in Network.cpp? I am more experienced with C than C++ and have tried a lot in order to understand all of this.
This is some of my thoughts of the structure, header and cpp files:
Main.cpp
#include "MAC.h"
#include "Network.h"
int main() {
MAC mac();
Network network(mac);
return 0;
}
Here is the MLME part to be shared:
MLME.h
#ifndef MLME_H_INCLUDED
#define MLME_H_INCLUDED
class MLME {
public:
MLME();
};
#endif
MLME.cpp
#include "MLME.h"
MLME::MLME() {}
The MAC class:
MAC.h
#ifndef MAC_H_INCLUDED
#define MAC_H_INCLUDED
#include "MLME.h"
class MAC {
private:
MLME mlme; // NULLED ?
public:
MAC();
MLME getMLME();
};
#endif
MAC.cpp
#include "MAC.h"
MAC::MAC() {
mlme = MLME:MLME();
}
MLME MAC::getMLME() {
return mlme;
}
The Network class:
Network.h
#ifndef NETWORK_H_INCLUDED
#define NETWORK_H_INCLUDED
#include "MLME.h"
class Network {
private:
MLME& mlme;
public:
Network(MAC mac);
};
#endif
Network.cpp
#include "Network.h"
class MAC;
Network::Network(MAC mac) {
mlme = mac.getMLME();
}
You're close, but:
The Network::Network constructor should take MAC by reference, like so: Network::Network(MAC& mac). Currently you take a copy, which means taking a copy of MLME as well.
In addition, the Network::Network constructor should use an initializer list to initialize mlme. So the full form would be:
Network::Network(MAC& mac) : mlme(mac.getMLME()) {}
MAC::getMLME() should return a reference to MLME: MLME& MAC::getMLME(). Otherwise you return a copy.
The explicit construction of MLME in the MAC constructor is not needed: it is already default-constructed.
You may want to prevent copying of MLME instances by saying MLME(const MLME&) = delete. If it is really a shared resource, you want any changes to go back to the shared instance. Making it impossible to copy MLME instances will prevent you from accidentally making or modifying a copy.
In your main function: MAC mac() does not do what you think it does. Remove the () or you get a "most vexing parse" error.
Main.cpp
int main() {
MAC mac;
Network network(mac);
mac.set(10);
mac.print();
network.print();
mac.set(11);
mac.print();
network.print();
return 0;
}
MLME.h
#ifndef MLME_H_INCLUDED
#define MLME_H_INCLUDED
#include "iostream"
using namespace std;
class MLME {
private:
int i;
public:
MLME();
void print();
void set(int in);
};
#endif
MLME.cpp
#include "MLME.h"
MLME::MLME() {}
void MLME::print() { cout << 'i' << i << endl; }
void MLME::set(int in) {
i = in;
}
MAC.h
#ifndef MAC_H_INCLUDED
#define MAC_H_INCLUDED
#include "MLME.h"
class MAC {
private:
MLME mlme; // NULLED ?
public:
MAC();
MLME& getMLME();
void print();
void set(int in);
};
#endif
MAC.cpp
#include "MAC.h"
MAC::MAC() {
mlme = MLME();
}
MLME& MAC::getMLME() {
return mlme;
}
void MAC::print() {
mlme.print();
}
void MAC::set(int in) {
mlme.set(in);
}
Network.h
#ifndef NETWORK_H_INCLUDED
#define NETWORK_H_INCLUDED
#include "MAC.h"
class Network {
private:
MLME& mlme;
public:
Network(MAC& mac);
void print();
};
#endif
Network.cpp
#include "Network.h"
Network::Network(MAC& mac) : mlme(mac.getMLME()) {}
void Network::print() {
mlme.print();
}
output
i10
i10
i11
i11
I have three files:
main.cpp
MyClass.cpp
MyClass.hpp
I have a library header file, "testLib.hpp", that I want to include in MyClass.hpp so that I can have one of testLib's objects be a class attribute.
I include MyClass.hpp in MyClass.cpp and in main.cpp. When attempting to compile the project, I get the following errors
MyClass.cpp multiple definition of 'testLib::testLib::function1()
obj/Release/main.o:main.cpp first defined here
MyClass.cpp multiple definition of 'testLib::testLib::function2()
obj/Release/main.o:main.cpp first defined here
and so on.
Both main.cpp and MyClass.cpp include MyClass.hpp (which includes testLib.hpp). Judging by the error, it looks like MyClass.cpp is attempting to include the library functions after they've already been included by main.cpp. However, I have include guards present in MyClass.hpp so I don't understand how it's trying to include MyClass.hpp twice.
Here's the code:
MyClass.hpp
#ifndef THIS_HEADER_H
#define THIS_HEADER_H
#include <stdint.h>
#include <iostream>
#include "testLib/testLib.hpp"
class MyClass
{
public:
void test();
int foo;
private:
uint32_t bar;
//I want to include an object from the library as part of this class
//TestLib::Device device;
};
#endif
MyClass.cpp
#include <stdio.h>
#include "MyClass.hpp"
void MyClass::test()
{
}
main.cpp
#include <iostream>
#include "MyClass.hpp"
using namespace std;
int main()
{
cout << "Hello world!" << endl;
return 0;
}
Any help would be greatly appreciated!
EDIT
I tried to hide the actual filenames to make the question more general and clear, but it seems like the problem might be resulting from 'testLib.hpp', which I did not write. That file is actually the following "sweep.hpp" file. I got the 'multiple definition of/first defined here' errors for each of the public functions in this file:
sweep.hpp
#ifndef SWEEP_DC649F4E94D3_HPP
#define SWEEP_DC649F4E94D3_HPP
/*
* C++ Wrapper around the low-level primitives.
* Automatically handles resource management.
*
* sweep::sweep - device to interact with
* sweep::scan - a full scan returned by the device
* sweep::sample - a single sample in a full scan
*
* On error sweep::device_error gets thrown.
*/
#include <cstdint>
#include <memory>
#include <stdexcept>
#include <vector>
#include <sweep/sweep.h>
namespace sweep {
// Error reporting
struct device_error final : std::runtime_error {
using base = std::runtime_error;
using base::base;
};
// Interface
struct sample {
const std::int32_t angle;
const std::int32_t distance;
const std::int32_t signal_strength;
};
struct scan {
std::vector<sample> samples;
};
class sweep {
public:
sweep(const char* port);
sweep(const char* port, std::int32_t bitrate);
void start_scanning();
void stop_scanning();
bool get_motor_ready();
std::int32_t get_motor_speed();
void set_motor_speed(std::int32_t speed);
std::int32_t get_sample_rate();
void set_sample_rate(std::int32_t speed);
scan get_scan();
void reset();
private:
std::unique_ptr<::sweep_device, decltype(&::sweep_device_destruct)> device;
};
// Implementation
namespace detail {
struct error_to_exception {
operator ::sweep_error_s*() { return &error; }
~error_to_exception() noexcept(false) {
if (error) {
device_error e{::sweep_error_message(error)};
::sweep_error_destruct(error);
throw e;
}
}
::sweep_error_s error = nullptr;
};
}
sweep::sweep(const char* port)
: device{::sweep_device_construct_simple(port, detail::error_to_exception{}), &::sweep_device_destruct} {}
sweep::sweep(const char* port, std::int32_t bitrate)
: device{::sweep_device_construct(port, bitrate, detail::error_to_exception{}), &::sweep_device_destruct} {}
void sweep::start_scanning() { ::sweep_device_start_scanning(device.get(), detail::error_to_exception{}); }
void sweep::stop_scanning() { ::sweep_device_stop_scanning(device.get(), detail::error_to_exception{}); }
bool sweep::get_motor_ready() { return ::sweep_device_get_motor_ready(device.get(), detail::error_to_exception{}); }
std::int32_t sweep::get_motor_speed() { return ::sweep_device_get_motor_speed(device.get(), detail::error_to_exception{}); }
void sweep::set_motor_speed(std::int32_t speed) {
::sweep_device_set_motor_speed(device.get(), speed, detail::error_to_exception{});
}
std::int32_t sweep::get_sample_rate() { return ::sweep_device_get_sample_rate(device.get(), detail::error_to_exception{}); }
void sweep::set_sample_rate(std::int32_t rate) {
::sweep_device_set_sample_rate(device.get(), rate, detail::error_to_exception{});
}
scan sweep::get_scan() {
using scan_owner = std::unique_ptr<::sweep_scan, decltype(&::sweep_scan_destruct)>;
scan_owner releasing_scan{::sweep_device_get_scan(device.get(), detail::error_to_exception{}), &::sweep_scan_destruct};
auto num_samples = ::sweep_scan_get_number_of_samples(releasing_scan.get());
scan result;
result.samples.reserve(num_samples);
for (std::int32_t n = 0; n < num_samples; ++n) {
auto angle = ::sweep_scan_get_angle(releasing_scan.get(), n);
auto distance = ::sweep_scan_get_distance(releasing_scan.get(), n);
auto signal = ::sweep_scan_get_signal_strength(releasing_scan.get(), n);
result.samples.push_back(sample{angle, distance, signal});
}
return result;
}
void sweep::reset() { ::sweep_device_reset(device.get(), detail::error_to_exception{}); }
} // ns
#endif
A simplified version of your problem:
buggy.hpp
int function() { return 0; }
main.cpp
#include "buggy.hpp"
int main() { return 0; }
other.cpp
#include "buggy.hpp"
The problem is that buggy.hpp is defining function, not just declaring. Once the header inclusion is expanded, that means function is declared in both main.cpp and other.cpp - and that is not allowed.
The fix is to declare function as inline which allows the function to be declared in multiple translation units.
inline int function() { return 0; }
In fact, allowing multiple definitions is the only meaning of inline to the C++ standard. Compilers may treat it as a hint that the function body may be expanded inline. Good ones won't; they are better at making that sort of decision that programmers).
I'm trying to make the following compile under VS 2008 SP1 C++ project, but the friend class statement doesn't seem to have any effect. (See error message in the last code snippet.)
What am I doing wrong with the friend definition?
// EncryptionTypes.h file
#pragma once
//#include "Encryption.h" //adding this line doesn't help
using namespace crypto;
struct FILE_DATA_CACHE{
FILE_DATA_CACHE()
{
};
~FILE_DATA_CACHE()
{
}
friend class CEncryption;
private:
bool _isIndexFileUsed()
{
return bResult;
}
};
then:
// Encryption.h
#pragma once
#include "EncryptionTypes.h"
namespace crypto
{
class CEncryption
{
public:
CEncryption(void);
~CEncryption(void);
private:
BOOL _openFile();
private:
FILE_DATA_CACHE gFData;
};
};
and lastly:
// Encryption.cpp
#include "StdAfx.h"
#include "Encryption.h"
namespace crypto
{
CEncryption::CEncryption(void)
{
}
CEncryption::~CEncryption(void)
{
}
void CEncryption::_openFile()
{
//The line below generates this error:
//1>.\Encryption.cpp(176) : error C2248: 'FILE_DATA_CACHE::_isIndexFileUsed' : cannot access private member declared in class 'FILE_DATA_CACHE'
//1> c:\users\blah-blah\EncryptionTypes.h(621) : see declaration of 'FILE_DATA_CACHE::_isIndexFileUsed'
//1> c:\users\blah-blah\EncryptionTypes.h(544) : see declaration of 'FILE_DATA_CACHE'
gFData._isIndexFileUsed();
}
};
You have a circular dependency problem.
Encryption.h needs FILE_DATA_CACHE, which is defined in EncryptionTypes.h.
EncryptionType.h needs CEncryption, which is defined in Encryption.h.
Fortunately, you can get by with using a forward declaration of CEncryption in EncryptionType.h.
Modify EncryptionType.h to:
// EncryptionTypes.h file
#pragma once
// Can't #include Encryption.h. That will lead to circular
// #includes.
namespace crypto
{
// Forward declaration of crypto::CEncryption
class CEncryption;
}
struct FILE_DATA_CACHE{
FILE_DATA_CACHE()
{
};
~FILE_DATA_CACHE()
{
}
friend class crypto::CEncryption;
private:
bool _isIndexFileUsed()
{
return bResult;
}
};
Sorry for the lack of a descriptive title.
I'm getting an error "one or more multiply defined symbols found"; to be more specific, I'm getting 46 of them. One for each function in my header/source files. Using Visual Studios 2013.
Here is the relevant source code:
augments.h
#ifndef AUGMENTS_H_
#define AUGMENTS_H_
namespace Augments {
// only used for pass-ins for constructors
enum class Weapon_Type {
sword
};
enum class Head_Type {
head
};
enum class Body_Type {
body
};
// the player (Monster) has a head, body and weapon
// that augments his abilities. This will mostly
// be the thing that draws to the screen for each
// augmentation, but more importantly it contains
// specific statistics about each one.
// So if there was a body that was able to fly,
// there would be a bool that denotes this ability.
class Head : public Actor {
const Head_Type type;
public:
Head(Head_Type);
void Update(float dt);
};
class Body : public Actor {
const Body_Type type;
public:
Body(Body_Type);
void Update(float dt);
};
class Weapon : public Actor {
const Weapon_Type type;
public:
Weapon(Weapon_Type);
void Update(float dt);
};
}
using AugHead = Augments::Head;
using AugBody = Augments::Body;
using AugWep = Augments::Weapon;
#endif
augments.cpp
#include "stdafx.h"
#include "Angel.h"
#include "Augments.h"
#include "LD33.h"
Augments::Head::Head(Augments::Head_Type x) : type(x) {
switch ( x ) {
case Head_Type::head:
SetSprite("Images\\head.png");
break;
};
};
void Augments::Head::Update(float dt) {
SetPosition(Game::thePlayer->GetPosition().X,
Game::thePlayer->GetPosition().Y-
MathUtil::ScreenToWorld(Vec2i(0,40)).Y);
};
Augments::Body::Body(Augments::Body_Type x) : type(x) {
switch ( x ) {
case Body_Type::body:
SetSprite("Images\\body.png");
break;
};
}
void Augments::Body::Update(float dt) {
SetPosition(Game::thePlayer->GetPosition().X,
Game::thePlayer->GetPosition().Y);
}
Augments::Weapon::Weapon(Augments::Weapon_Type x ) : type(x) {
switch ( x ) {
case Weapon_Type::sword:
SetSprite("Images\\weapon.png");
break;
}
}
void Augments::Weapon::Update(float dt) {
SetPosition(Game::thePlayer->GetPosition().X,
Game::thePlayer->GetPosition().Y-
MathUtil::ScreenToWorld(Vec2i(0,-40)).Y);
}
monster.h
// monster related
#include "Augments.h"
#include "Angel.h"
#ifndef MONSTER_H_
#define MONSTER_H_
namespace Player {
// contains information like health attack etc
// but more important body types
class Monster : public PhysicsActor {
int max_health, curr_health;
int attack_damage;
Augments::Head* frame_head;
Augments::Weapon* frame_weapon;
Augments::Body* frame_body;
public:
void Refresh(float dt);
int R_Max_Health() const;
int R_Curr_Health() const;
int R_Attack_Damage() const;
Augments::Head* R_Frame_Head();
Augments::Weapon* R_Frame_Weapon();
Augments::Body* R_Frame_Body();
void Set_Max_Health(int);
void Set_Curr_Health(int);
void Add_Curr_Health(int);
void Set_Attack_Damage(int);
// will automatically remove old
// actors from the stage and deallocate
void Set_Frame_Head(Augments::Head_Type);
void Set_Frame_Weapon(Augments::Weapon_Type);
void Set_Frame_Body(Augments::Body_Type);
Monster(Augments::Head_Type,
Augments::Weapon_Type,
Augments::Body_Type);
};
};
using PlMonster = Player::Monster;
#endif
monster.cpp
#include "stdafx.h"
#include "Monster.h"
#include "Augments.h"
#include "Angel.h"
void Player::Monster::Refresh(float dt) {
};
int Player::Monster::R_Max_Health() const { return max_health; }
int Player::Monster::R_Curr_Health() const { return curr_health; }
int Player::Monster::R_Attack_Damage() const { return attack_damage; }
Augments::Head* Player::Monster::R_Frame_Head() { return frame_head; }
Augments::Body* Player::Monster::R_Frame_Body() { return frame_body; }
Augments::Weapon* Player::Monster::R_Frame_Weapon() { return frame_weapon; }
void Player::Monster::Set_Max_Health(int x) { max_health = x; }
void Player::Monster::Set_Curr_Health(int x) { curr_health = x; }
void Player::Monster::Add_Curr_Health(int x) { curr_health += x; }
void Player::Monster::Set_Attack_Damage(int x) { attack_damage = x; }
void Player::Monster::Set_Frame_Head(Augments::Head_Type x) {
if ( frame_head != nullptr ) {
frame_head->Destroy();
delete frame_head;
frame_head = nullptr;
}
frame_head = new Augments::Head(x);
theWorld.Add(frame_head);
};
void Player::Monster::Set_Frame_Weapon(Augments::Weapon_Type x) {
if ( frame_weapon != nullptr ) {
theWorld.Remove(frame_weapon);
delete frame_weapon;
frame_weapon = nullptr;
}
frame_weapon = new Augments::Weapon(x);
theWorld.Add(frame_weapon);
};
void Player::Monster::Set_Frame_Body(Augments::Body_Type x) {
if ( frame_body != nullptr ) {
theWorld.Remove(frame_body);
delete frame_body;
frame_body = nullptr;
}
frame_body = new Augments::Body(x);
theWorld.Add(frame_body);
};
Player::Monster::Monster(Augments::Head_Type head,
Augments::Weapon_Type weapon,
Augments::Body_Type body) {
frame_body = nullptr;
frame_head = nullptr;
frame_weapon = nullptr;
Set_Frame_Body(body);
Set_Frame_Head(head);
Set_Frame_Weapon(weapon);
}
source.cpp
#include "stdafx.h"
#include "LD33.h"
#include "Angel.h"
int main ( ) {
Game::Initialize();
theWorld.StartGame();
theWorld.Destroy();
return 0;
}
Errors include things such as:
Error 43 error LNK2005: "public: int __thiscall Player::Monster::R_Attack_Damage(void)const " (?R_Attack_Damage#Monster#Player##QBEHXZ) already defined in Augments.obj C:\Users\The Shire\Desktop\ludum_dare\ludumdare33\Code\ClientGame\source.obj ClientGame
Error 3 error LNK2005: "public: void __thiscall Player::Monster::Set_Frame_Body(enum Augments::Body_Type)" (?Set_Frame_Body#Monster#Player##QAEXW4Body_Type#Augments###Z) already defined in Augments.obj C:\Users\The Shire\Desktop\ludum_dare\ludumdare33\Code\ClientGame\LD33.obj ClientGame
And it pretty much states similar for every single function in Monster.
Sorry for just dumping a ton of code. I've been trying to debug it for awhile but couldn't come up with any reasonable solution. I have the include guards, I don't see any namespace conflicts, and everything that needs to be defined is outside of the header files. I can't find anything in augments.h that would be causing this. I also thought it might be the enums, but replacing them with just int did not work either.
I'm thinking it might be the order of the include files? hmm. Maybe there's somehow multiple source files somewhere but I would have no clue as to how. Any help?
Had included Monster.cpp in another header file on accident! Oops
I have a Problem and i am completely stuck.
First i show you the code:
Config for Building(NarviConfig.h):
#pragma once;
namespace Narvi
{
#ifdef NARVI_EXPORTS
#define _NarviExport __declspec(dllexport)
#else
#define _NarviExport __declspec(dllimport)
#endif
}
//-------------------------------------------
I have 2 Classes in a DLL like this:
The first One(NarviRoot.h):
Header:
#pragma once
#include "NarviConfig.h"
#include "NarviWindow.h"
namespace Narvi
{
class _NarviExport NarviRoot
{
public:
NarviRoot();
~NarviRoot();
public:
bool Init(void);
private:
NarviWindow* mWindow;
};
}
Source:-----------------------------
#include "NarviRoot.h"
namespace Narvi
{
NarviRoot::NarviRoot()
{
}
NarviRoot::~NarviRoot()
{
delete mWindow;
}
bool NarviRoot::Init(void)
{
mWindow = new NarviWindow();
return true;
}
}
//-----------------------------------------------------------------
The window(NarviWindow.h):
Header
#pragma once
#include "NarviConfig.h"
namespace Narvi
{
class _NarviExport NarviWindow
{
public:
NarviWindow();
~NarviWindow();
};
}
Source:--------------------------------
#include "NarviWindow.h"
namespace Narvi
{
NarviWindow::NarviWindow()
{
}
NarviWindow::~NarviWindow()
{
}
}
And this is my Testapp
mRoot = new Narvi::NarviRoot();
mRoot->Init();
It seems to work, but the program crashes when calling
mWindow = new NarviWindow();
Inside of
bool NarviRoot::Init(void)
{
mWindow = new NarviWindow();
return true;
}
and i can't figure out why.
If i write:
NarviWindow* mWindow = new NarviWindow();
it doesn't crash.
The constructor of NarviWindow is doing nothing, but it seems he can't access the private member mWindow.
I am pretty sure it is a simple error i made, but i can't see the wood for the trees.
Thank you! :)