Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
10 years, 5 months ago.
Classes question
Dear all,
I am planning to create an application that will write on a text LCD through a I2C IO Expander (PCF8574).
I have a custom made library for generating a menu functionality on a display, still I would also like to write data from the main procedure or other function from different cpp files.
The question is how to achieve this in the right way.
What I have tested already, was to create a "common.h" with the following content (and load it in every .h file):
common.h file
#ifndef __COMMON_H_INCLUDED__ #define __COMMON_H_INCLUDED__ #include "mbed.h" I2C i2c_bus_2(PTE0, PTE1); TextLCD_I2C lcd(&i2c_bus_2, 0x40, TextLCD::LCD20x4); // I2C bus, PCF8574 Slaveaddress, LCD Type #endif
Reading about C++ classes I found out that this is not a healthy way for some reasons. Could you please guide me or explain how to create my application the right way.
Thanks, Mircea.
1 Answer
10 years, 5 months ago.
Hi Mircea Murar,
don't place objects (variable, class, etc..) definitions in a header file, you might end up with multiply definitions (waste space) .
You can create an object in one code file (translation unit) globally and export it through declaration in a header file, so it becomes visible to other translations units.
The examples can be found here for example http://mylinuxbook.com/the-concept-of-extern-variables-in-c/.
The another way to do it, it's to create it locally (on stack/heap), and pass it around the program as parameter using a pointer type.
See this question http://programmers.stackexchange.com/questions/222626/is-it-better-to-use-an-external-variable-or-to-pass-around-a-pointer
Regards,
0xc0170
So in this instance you would want:
common.h
#ifndef __COMMON_H_INCLUDED__ #define __COMMON_H_INCLUDED__ #include "mbed.h" #include "TextLCD_I2C.h" // the header file that defines your LCD driver extern I2C i2c_bus_2; extern TextLCD_I2C lcd; #endif
main.cpp
#include "common.h" I2C i2c_bus_2(PTE0, PTE1); TextLCD_I2C lcd(&i2c_bus_2, 0x40, TextLCD::LCD20x4); // I2C bus, PCF8574 Slaveaddress, LCD
This way anything that includes common.h can assess both i2c_bus_2 and lcd directly but they are only declared in a single file.
posted by 30 May 2014