Thread: Having the same object in multiple files

  1. #1
    Registered User
    Join Date
    Mar 2016
    Posts
    36

    Having the same object in multiple files

    I am trying to put an object for Serial Communication in multiple classes

    So I made a header file just for that object

    Code:
    #ifndef _EXTERN_SERIAL_COMM_H_
    #define _EXTERN_SERIAL_COMM_H_
    
    #include "SerialPort.h"
    extern SerialPort serialPort(4800);
    
    #endif
    But I am getting compiler error: "Multiple definition of serialPort"

    So I included the header in my interface

    Code:
    #pragma once
    
    #ifndef _JOYSTICK_STATE_H_
    #define _JOYSTICK_STATE_H_
    
    #include <stdint.h>
    #include "ExternSerialComm.h"
    class Joystick;
    
    #ifndef NULL
    #define NULL 0
    #endif
    
    class JoystickState
    {
        protected:
            JoystickState() {};
        public:
            virtual void handleCoordinates(int, int, Joystick&) = 0;
    };
    
    #endif
    I am getting error in my child classes

    Code:
    #ifndef _DOWN_JOYSTICK_STATE_H_
    #define _DOWN_JOYSTICK_STATE_H_
    
    #include "JoystickState.h"
    #include "Joystick.h"
    #include "IdleJoystickState.h"
    
    
    class DownJoystickState : public JoystickState
    {
    private:
        static JoystickState* sInstance;
    public:
        static JoystickState* getInstance();
        void handleCoordinates(int nX, int nY, Joystick& joystick);
    };
    
    #endif

    Code:
    #pragma once
    #ifndef _IDLE_JOYSTICK_STATE_H_
    #define _IDLE_JOYSTICK_STATE_H_
    
    #include "Joystick.h"
    #include "JoystickState.h"
    #include "DownJoystickState.h"
    #include "RightJoystickState.h"
    #include "LeftJoystickState.h"
    #include "RightJoystickState.h"
    #include "UpJoystickState.h"
    
    #ifndef POSITIONS_LENGTH
    #define POSITIONS_LENGTH    3
    #endif // !POSITIONS_LENGTH
    
    #ifndef MAX_X_POSITION
    #define MAX_X_POSITION        1000
    #endif // !1
    
    #ifndef MIN_X_POSITION
    #define MIN_X_POSITION        20
    #endif // !
    
    #ifndef MAX_Y_POSITION
    #define MAX_Y_POSITION        1000
    #endif // MAX_Y_POSITION
    
    #ifndef MIN_Y_POSITION
    #define MIN_Y_POSITION        20
    #endif // !1
    
    #ifndef MODE_KORISTI
    #define MODE_KORISTI        0
    #endif // !1
    
    #ifndef MODE_POSTAVI
    #define MODE_POSTAVI        1
    #endif // !MODE_POSTAVI
    
    #define NOK -1
    
    class IdleJoystickState : public JoystickState
    {
    private:
        static JoystickState* sInstance;
        int8_t getBufferFreeIndex(Joystick& joystick);
    
    public:
        static JoystickState* getInstance();
    
        void handleCoordinates(int nX, int nY, Joystick& joystick);
    };
    #endif
    and so on...

    I do not know what I am doing wrong. I found this solution on the internet.

    Any better solution for doing global object?

  2. #2
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    In the .h file you include everywhere you need it, you put
    extern SerialPort serialPort;

    In exactly ONE .cpp file, you put
    SerialPort serialPort(4800);
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #3
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    A simple example using an extern variable.
    Code:
    // a.cpp
    
    // This defines (creates) the actual variable
    // in this object file.
    int externInt = 42;
    
    int main() {
        void func1();
        func1();
        return 0;
    }
    
    
    // =============================================
    // b.cpp
    #include <iostream>
    
    void func1() {
    
        // This tells the compiler that the variable exists
        // elsewhere and will be resolved during linking.
        // This variable needs to be globally defined in some
        // other source file whose object code will be linked
        // with this file's object code.
        extern int externInt;
    
        // It's really just the same as this, which also tells
        // the compiler that something exists elsewhere, so it
        // should just assume that it exists (with this type)
        // and go ahead and compile, leaving the actual "link"
        // to  this function unresolved for now.
        void func2();
    
        std::cout << externInt << '\n';
        externInt *= 2;
        func2();
    }
    
    
    // =============================================
    // c.cpp
    #include <iostream>
    
    void func2() {
        extern int externInt;
        std::cout << externInt << '\n';
    }
    Code:
    $ g++ -c a.cpp     # creates a.o
    $ g++ -c b.cpp     # creates b.o
    $ g++ -c c.cpp     # creates c.o
    $ g++ a.o b.o c.o -o prog  # links the .o files into prog
                               # resolving outstanding links
                               # to func1, func2, and externInt
                               # (as well as cout and the ostream << overload)
    $ ./prog           # run prog (in current directory)
    42
    84

  4. #4
    Registered User
    Join Date
    Mar 2016
    Posts
    36
    Quote Originally Posted by Salem View Post
    In the .h file you include everywhere you need it, you put
    extern SerialPort serialPort;

    In exactly ONE .cpp file, you put
    SerialPort serialPort(4800);
    Sorry I am trying to understand your post, but I think I do not understand it, could you give some random example.


    I put extern SerialPort serialPort; ,in every .h file where it is used (used in .cpp file of course):

    Code:
    #ifndef _DOWN_JOYSTICK_STATE_H_
    #define _DOWN_JOYSTICK_STATE_H_
    
    #include "JoystickState.h"
    #include "Joystick.h"
    #include "IdleJoystickState.h"
    
    extern SerialPort serialPort;
    
    class DownJoystickState : public JoystickState
    {
    private:
        static JoystickState* sInstance;
    public:
        static JoystickState* getInstance();
        void handleCoordinates(int nX, int nY, Joystick& joystick);
    };
    
    #endif
    Code:
    #ifndef _LEFT_JOYSTICK_STATE_H_
    #define _LEFT_JOYSTICK_STATE_H_
    
    #include "JoystickState.h"
    #include "Joystick.h"
    #include "IdleJoystickState.h"
    
    extern SerialPort serialPort;
    
    class LeftJoystickState : public JoystickState
    {
    private:
        static JoystickState* sInstance;
    public:
        static JoystickState* getInstance();
        void handleCoordinates(int nX, int nY, Joystick& joystick);
    };
    
    #endif
    Code:
    #ifndef _JOYSTICK_H_
    #define _JOYSTICK_H_
    
    #include "JoystickState.h"
    #include "IdleJoystickState.h"
    
    
    #define POSITIONS_LENGTH    4
    
    #define MAX_X_POSITION        1000
    #define MIN_X_POSITION        20
    #define MAX_Y_POSITION        1000
    #define MIN_Y_POSITION        20
    
    #define MODE_KORISTI        0
    #define MODE_POSTAVI        1
    
    #define INVALID_PARAMETER   -1
    #define IN_DEADZONE          0
    #define NOT_IN_DEADZONE      1
    
    extern SerialPort serialPort;
    
    class Joystick
    {
    
    private:
        uint8_t currentMode;
        JoystickState* currentState;
    public:
        JoystickState* position_states[POSITIONS_LENGTH];
    
    public:
        Joystick();
    
        void setMode(int newMode);
    
        int getMode();
    
        Joystick& operator=(const Joystick& other);
    
        friend bool operator==(const Joystick& joystickOne, const Joystick& joystickTwo);
        void handlePositions(void);
        int8_t getZone(int nX, int nY);
        bool isPasswordSet(void);
        void changeState(JoystickState* newState);
    
    };
    
    #endif // !_JOYSTICK_H_
    etc...


    Also in main.cpp I instantiated an object serialPort(4600); before all the includes, but now I get serialPort was not declared in this scope and serialPort does not name a type errors
    Code:
    
    #ifndef F_CPU
    #define F_CPU 1000000UL
    #endif
    
    #include "SerialPort.h"
    SerialPort serialPort(4600);
    
    #include "avr/io.h"
    #include "avr/interrupt.h"
    #include <util/delay.h>
    
    #include <stdlib.h>
    #include "i2cmaster.h"
    #include "I2C.h"
    #include "new.h"
    
    #include "AnalogConverter.h"
    
    // This include uses serialPort object
    #include "Joystick.h"
    
    Joystick joystick;
    
    void start(void)
    {
        uint8_t nKeyPressed;
        Joystick tempJoystick;
    
        serialPort.write( "Enter the key: ");
        //cin >> nKeyPressed;
    
        if (nKeyPressed == 'P')
        {
            serialPort.write( "Postavi Mode running!");
            joystick.setMode(MODE_POSTAVI);
        }
        else if (nKeyPressed == 'K')
        {
            serialPort.write("Koristi Mode running!");
            joystick.setMode(MODE_KORISTI);
        }
    
        tempJoystick.handlePositions();
    
        if (joystick.getMode() == MODE_POSTAVI)
        {
            // Copy values from one object to another
            joystick = tempJoystick;
        }
        else if (joystick.getMode() == MODE_KORISTI)
        {
            // Check if user entered right combination
            if (joystick == tempJoystick)
            {
                serialPort.write("Suitcase opened");
            }
            else
            {
                serialPort.write("Invalid combination");
            }
        }
        else
        {
            // Handle error
        }
    
        serialPort.write("");
    }
    
    //AnalogConverter analog;
    
    int main (void)
    {
        DDRC = 0xFF;
        DDRA &= ~(1 << PINA0);
        
        uint16_t readVal;    
        AnalogConverter_Init();
    
        while (true)
        {            
            readVal = AnalogConverter_Read(0);
            if (readVal != CONVERTER_NO_NEW_DATA)
            {
                serialPort.write("Analog Read");
                serialPort.write(readVal);
                serialPort.write("");
            }
            else
            {
                serialPort.write("No new data from ADC");
            }
        }
    }
    EDIT:

    I forgot to add #include "SerialPort.h" in every .h file where I wrote extern SerialPort serialPort; ... It compiled, thank you, gonna check now if it works!
    Last edited by ZeroesAndOnes; 05-06-2017 at 09:48 AM.

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,661
    > I put extern SerialPort serialPort; ,in every .h file where it is used (used in .cpp file of course):
    Then you did it wrong.

    You put the extern in ONE .h file - preferably one related to the rest of the serial functionality.

    You #include that .h file in all the .cpp files where you need serial functionality.

    In ONE .cpp file, you put the actual definition.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 4
    Last Post: 02-13-2013, 05:52 PM
  2. Multiple Source Files, make files, scope, include
    By thetinman in forum C++ Programming
    Replies: 13
    Last Post: 11-05-2008, 11:37 PM
  3. C++ Object Oriented and Multiple Files Basics?
    By markcls in forum C++ Programming
    Replies: 4
    Last Post: 03-25-2007, 12:21 PM
  4. Multiple Object Declarations
    By sean in forum C# Programming
    Replies: 3
    Last Post: 09-26-2004, 10:42 PM
  5. Replies: 1
    Last Post: 05-01-2003, 02:52 PM

Tags for this Thread