HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Serial port library across different compilers

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
compilersserialdifferentlibraryacrossport

Problem

I'm writing a C++ library with MinGW (4.8.0, DW2, POSIX) compiler. But this library must be used by another compiler. I've read this post, so I've re-written the C++ library interface in this way:

```
#ifndef SERIALPORT_H
#define SERIALPORT_H

#include // size_t
#include // unique_ptr

#if defined( _MSC_VER ) || defined( __MINGW32__ ) || defined( __MINGW64__ )
# define SERIALPORT_IMPORT __declspec( dllimport )
# define SERIALPORT_EXPORT __declspec( dllexport )
# define SERIALPORT_CALL __stdcall
#elif defined( __GNUG__ ) && !defined( WIN32 )
# define SERIALPORT_IMPORT
# define SERIALPORT_EXPORT __attribute__ ((visibility ("default")))
#else
# define SERIALPORT_IMPORT
# define SERIALPORT_EXPORT
#endif

#if defined( SERIALPORT_EXPORTS )
# define SERIALPORT_API SERIALPORT_EXPORT
#else
# define SERIALPORT_API SERIALPORT_IMPORT
#endif

namespace serialport {

/**
* @brief Milliseconds_t rappresent a duration of time expressed in milliseconds
*/
typedef unsigned long Milliseconds_t;

/**
* Possible read return value.
*/
enum ReadStatus
{
SERIAL_OK,
SERIAL_TIMEOUT,
SERIAL_ERROR
};

/**
* Interface to access to a serial port
*/
class ISerialPort {
public:
/**
* @brief operator delete overload the delete operator so we can destroy
* class inside shared library bounds.
*/
void operator delete( void* p )
{
if ( p )
{
ISerialPort* s = static_cast( p );
s->destroy();
}
}

/**
* Get serial port path
*/
virtual const char* SERIALPORT_CALL getDeviceName() const = 0;

/**
* Get serial port baudrate
*/
virtual int SERIALPORT_CALL baudrate() const = 0;

/**
* Flush serial port rx and tx buffers.
*/
virtual void SERIALPORT_CALL flush() = 0;

/**
* @brief setTimeout set the serial port timeout
* @param timeout_ms timeout in milliseconds
*/
virtual void SERIALPORT_CAL

Solution

-
You should just include ` in order to use std::size_t. Including seems unnecessary if you're not actually going to utilize anything else.

-
Since this is C++11, you can now use strongly-typed
enums over plain ones. One difference is that plain enums are implicitly cast to int, whereas strongly-typed ones must be explicitly cast in order to not be implicitly cast as well.

-
Both of these classes have no
private fields, so they can just become structs, which are public` by default.

Context

StackExchange Code Review Q#33386, answer score: 9

Revisions (0)

No revisions yet.