2

I work with pthreads and I want to use this code:

if(pthread_mutex_lock(&lock)){
        cout<<"error"<<endl;
        return ERROR;
    }

my question is should I do it with #define or should I do it with inline function:

inline void func() {

if(pthread_mutex_lock(&lock)){
        cout<<"error"<<endl;
        return ERROR;
    }

}

Should the function be static? such as:

static inline void func() 
0x90
  • 39,472
  • 36
  • 165
  • 245

4 Answers4

3

You shouldn't do anything with macros if you can help it (and here, you can help it).

If your function lives and is used solely in a cpp it should be in an unnamed namespace...

namespace
{
    void func(){/*...*/}
}

If it's declared in a header and meant to be used from many other cpps it should not be static or in an unnamed namespace.

David
  • 27,652
  • 18
  • 89
  • 138
  • +1 just for 'You shouldn't do anything with macros if you can help it'. – Martin James May 03 '12 at 21:09
  • I don't understand at all what the namespace has to do with the question. – Michael Burr May 04 '12 at 15:05
  • @MichaelBurr He asked if he should use `static`, which in global namespace specifies internal linkage - but that use of static has been replaced by using unnamed namespaces instead. – David May 07 '12 at 14:24
2

inline is irrelevant. You do realize that you'll have to make the function take as a parameter a reference to whatever type lock is, and then allow a return type.

So do something like:

ErrorType func(LockType &lock) 
{
     if(pthread_mutex_lock(&lock))
     { 
           prtSysErr(!DIRECT_EXIT,!FATAL); 
           return ERROR; 
     } 
     return NOERROR;
} 

Then call it like:

if(func(lock)==ERROR)
{
     return ERROR;
}

I'm calling the type of the lock LockType and the type of the error ErrorType for you to place in whatever they are. I'm also assuming the value of no error being called NOERROR similarly.

Yeah, and don't call it func, and put it in a namespace like @Dave said.

Chris A.
  • 6,817
  • 2
  • 25
  • 43
2

The C++ way would be to take the lock in a RAII way and to throw an exception from the constructor if locking fails. See this example.

Community
  • 1
  • 1
stefaanv
  • 14,072
  • 2
  • 31
  • 53
1

No, You should not use macro.
You can mark it as inline or just use it as a normal function the compiler will inline it if it finds an appropriate candidate for doing so.
Note, that if you mark the function as static you can only use it within the Translation Unit where you declare it.

Why?

With functions you get type checking of the function arguments being passed you don't get that with macro.
Also, with an macro you are exposed to silly and strange side effects which the macro might produce.

Alok Save
  • 202,538
  • 53
  • 430
  • 533