Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create multithread logger in c++

I want to create a multithread logger in c++ which can be called from c code as well.

This is in my source.cpp file:

#include <cstdlib>
#include <iostream>
#include <thread>
#include "source.h"
using namespace std;

#ifdef __cplusplus
extern "C" {
#endif
class thread_obj {
public:
    void operator()(float* x)
    {
        printf("value: %d", x);
    }
};

void log(float value)
{
    thread th1(thread_obj(), value);
    th1.join();
}

#ifdef __cplusplus
}
#endif

And this is in source.h:

#ifdef __cplusplus
extern "C" {
#endif
    void log(float value);
#ifdef __cplusplus
}
#endif

And now I want to use this from a C file like: log(myFloatValue);, of course with included header file.

But I got some strange errors, like:

Error   C2672   'invoke': no matching overloaded function found myproj C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\thread   43  
Error   C2893   Failed to specialize function template 'unknown-type std::invoke(_Callable &&,_Ty1 &&,_Types2 &&...) noexcept(<expr>)'  myproj C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\thread   39  
Error   C2780   'unknown-type std::invoke(_Callable &&) noexcept(<expr>)': expects 1 arguments - 2 provided hackatlon_0_0_1 C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.27.29110\include\thread  39  

My question is, how can I do this, or how can I solve these errors?

like image 202
alma korte Avatar asked Nov 20 '25 19:11

alma korte


1 Answers

There are multiple problems with your code:

  1. argument for operator() should be float x NOT float* since this is what you are passing to thread
  2. your log function conflicts with standard math log. Either change function name or put it into different namespace
  3. printf using format specifier "%d". It should be "%f" since input is float
  4. You don't need to put extern "C" for classes. You are avoiding name mangling only for log function which need to be called from c file.
like image 121
Shailesh Avatar answered Nov 23 '25 09:11

Shailesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!