How to make a simple structure visible in different cpp file - struct

I have a structure defined in main.cpp file and i want that same structure with value to be visible in other cpp file.
I tried this and this is way out of understanding for me as a beginner. So i re-ask the initial question again but in a simple way.
main.cpp
#include<iostream>
extern struct abc
{
int a;
std::string bla_bla;
};
void display(abc (&)[2]);
int main(void)
{
abc put[2];
put[0] = {10,"Apple"};
put[1] = {20,"Ball"};
display(put);
}
other.cpp
#include <iostream>
extern abc;
void display(abc (&put)[2])
{
std::cout << put[0].a << '\t' << put[0].bla_bla << std::endl;
std::cout << put[1].a << '\t' << put[1].bla_bla << std::endl;
}
it shows error a storage class can only be specified for objects and functions
and i am using c++17
is there any way to make that one structure visible to every cpp?
thanks in advance
EDIT: I got it need to keep the struct in .h file

Related

C++ Locking stream operators with mutex

I need to lock stdout in my logging application to prevent string interleaving in multi-thread applications logging to stdout. Can't figure out how to use move constructor or std::move or sth else to move unique_lock to another object.
I created objects for setting configs and encapsulation and figured out how to lock stdout with static std::mutex to lock from these objects (called shards).
Something like this works for me:
l->log(1, "Test message 1");
While that is fine and could be implemented with templates and variable number of parameters I would like to approach more stream-like possibilities. I am looking for something like this:
*l << "Module id: " << 42 << "value: " << 42 << std::endl;
I dont want to force users to precompute string with concatenation and to_string(42) I just want to find a way to lock stdout.
My approach so far was to create operator << and another object locked stream, as was suggested in other answers. Things is I can't figure how to move mutex to another object. My code:
locked_stream& shard::operator<<(int num)
{
static std::mutex _out_mutex;
std::unique_lock<std::mutex> lock(_out_mutex);
//std::lock_guard<std::mutex> lock (_out_mutex);
std::cout << std::to_string(num) << "(s)";
locked_stream s;
return s;
}
After outputting input to std::cout I woould like to move lock into object stream.
In this case, I would be careful not to use static locks in functions, as you will get a different lock for each stream operator you create.
What you need is to lock some "output lock" when a stream is created, and unlock it when the stream is destroyed. You can piggie back on existing stream operations if you're just wrapping std::ostream. Here's a working implementation:
#include <mutex>
#include <iostream>
class locked_stream
{
static std::mutex s_out_mutex;
std::unique_lock<std::mutex> lock_;
std::ostream* stream_; // can't make this reference so we can move
public:
locked_stream(std::ostream& stream)
: lock_(s_out_mutex)
, stream_(&stream)
{ }
locked_stream(locked_stream&& other)
: lock_(std::move(other.lock_))
, stream_(other.stream_)
{
other.stream_ = nullptr;
}
friend locked_stream&& operator << (locked_stream&& s, std::ostream& (*arg)(std::ostream&))
{
(*s.stream_) << arg;
return std::move(s);
}
template <typename Arg>
friend locked_stream&& operator << (locked_stream&& s, Arg&& arg)
{
(*s.stream_) << std::forward<Arg>(arg);
return std::move(s);
}
};
std::mutex locked_stream::s_out_mutex{};
locked_stream locked_cout()
{
return locked_stream(std::cout);
}
int main (int argc, char * argv[])
{
locked_cout() << "hello world: " << 1 << 3.14 << std::endl;
return 0;
}
Here it is on ideone: https://ideone.com/HezJBD
Also, forgive me, but there will be a mix of spaces and tabs up there because of online editors being awkward.

std::async, libc++ with clang33 does not work under Linux

I have a really simple program that works with clang33 under OSX. However if I try to run the same program under Linux it fails. Has anyone got std::asynch to work with clang33 under Linux (CentoOS)?
#include <iostream>
#include <future>
#include <thread>
int main() {
// future from a packaged_task
std::packaged_task<int()> task([]() {
return 7;
}); // wrap the function
std::future<int> f1 = task.get_future(); // get a future
std::thread(std::move(task)).detach(); // launch on a thread
// future from an async()
std::future<int> f2 = std::async(std::launch::async, []() {
return 8;
});
// future from a promise
std::promise<int> p;
std::future<int> f3 = p.get_future();
std::thread([](std::promise<int> & p) {
p.set_value(9);
},
std::ref(p)).detach();
std::cout << "Waiting..." << std::flush;
f1.wait();
f2.wait();
f3.wait();
std::cout << "Done!\nResults are: " << f1.get() << ' ' << f2.get() << ' '
<< f3.get() << '\n';
}
The above example works with trunk/198686 when I compile libc++ with cxxabi. However now I have encountered another problem:
#include <iostream>
#include <vector>
#include <exception>
int main () {
std::vector<int> foo;
try {
foo.at(1);
}
catch (std::exception& e) {
std::cerr << "exception caught: " << e.what() << '\n';
}
std::cout << "Works" << '\n';
return 0;
}
The example code above generates the following expected output under OS X:
exception caught: vector
Works
Under Linux I get the following output:
exception caught: Segmentation fault
I have debugged the code and segmentation fault occurs inside the destructor of logic_error (stdexcept.cpp, line 137). Does anyone have any suggestions?
BTW: Its no longer possible to compile libc++ using the libsupc++ method.
I have actually got everything to work. The above problems occurs with r198686. I checked out the same revision as #BenPope and then everything works as expected.
Thanks,
Patrik

Why does casting a string pointer to a void pointer and back cause the string data to dissappear? (Opencv)

I'm trying to create a function that initializes all my mouse handlers for every OpenCV window in one place. The code works in the main loop, but not inside my function (Yes, I am passing by reference).
The problem seems to stem from passing a pointer to the string - when it comes out the other side it won't successfully dereference (*). What gives?
Here's a minimalist example of what I'm talking about (It sets the mouse handlers for two identical windows - one window works, the other window doesnt):
// mouse problem.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include "opencv2/core/core.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <string.h>
#include <iostream> //for cout, cin
using namespace std;
using namespace cv;
void onMouse(int event, int x, int y, int flags, void* param){
string windowname = *((string*)param); //just recasting the void* we passed into the mousehandler to string
if(windowname.empty()){
cout << "ERROR.";
}else{
cout << "SUCCESS for window:" << windowname;
}
cout << " param: "<< param << " windowname: "<< windowname << "\n";
}
void initializer(const string& name){
namedWindow( name, CV_WINDOW_AUTOSIZE );
cout << " initializing mouse handler for " << name << " with string at address :" << &name << "\n";
setMouseCallback(name, onMouse, (void*)&name); //this line is exactly the same as the other setmousecallback line
}
int _tmain(int argc, _TCHAR* argv[]){
string name; Mat src; VideoCapture cap(0); cap >> src; // get a single frame from camera
//this works just fine
name = "frameA";
namedWindow( name, CV_WINDOW_AUTOSIZE );
cout << " initializing mouse handler for " << name << " with string at address :" << &name << "\n";
setMouseCallback(name, onMouse, (void*)&name);
//this fails even though it contains the same code and we pass by reference
initializer("frameB");
imshow("frameA",src); imshow("frameB",src); //display frame - mouseing over them triggers the OnMouse() event
while(true){ //loop forever
waitKey(30);
}
return 0;
}
And here is the result after I mouseover each window once.
What really KILLS me is that, as you can see in the picture, the address of the string is successfully recognized! And no errors on casting it to a string! But when I de-reference it, it says its empty!
Yes, I did try to avoid using Void*. Sadly, I cannot avoid the void. OpenCV requires a void to be the last argument of any mousehandler function :(
The problem has nothing to do with the casts. You are keeping a pointer to a temporary string object, and are trying to dereference that pointer after the object has gone out of scope.
The following:
initializer("frameB");
is equivalent to:
initializer(std::string("frameB"));
In other words, a temporary is created, and the function takes and keeps the address of that temporary. Since the temporary disappears at the end of the statement, you are left with a dangling pointer.

XCode Boost Thread Example Compile Error

Here's my basic boost code
#include <iostream>
#include <boost/thread.hpp>
using namespace boost;
using namespace boost::this_thread;
using namespace std;
// Global function called by thread
void GlobalFunction()
{
for (int i=0;i<10;++i)
{
cout << i << "Do something in parallel with main method." << endl;
boost::this_thread::yield();
}
}
void GlobalThreadTest()
{
boost::thread t(&GlobalFunction);
for (int i = 0; i<10; ++i) {
cout << i << "Do something in main method. " << endl;
}
}
int main(int argc, const char * argv[])
{
GlobalThreadTest();
return 0;
}
I'm getting lots of errors like this from xcode
(null): "boost::this_thread::yield()", referenced from:
(null): "boost::detail::thread_data_base::~thread_data_base()",
referenced from: (null): "boost::system::system_category()",
referenced from: (null): "boost::system::generic_category()",
referenced from: (null): "boost::thread::start_thread()", referenced
from:
I have installed boost using macports and the header search paths in xcode is set to
/opt/local/include/
This contains all the .hpp files.
2 Questions
Does boost create *.o files if so where are they stored?
How do I get xcode 4.2 to work with this boost thread example? If there is a flag I have to set, which parameter in xcode 4.2 do I set it in?
Thanks.

How do I use an enum type external from a header file?

class Board
{
public:
enum Player {X = -1, O, E};
bool win(Player P); // A function that returns true if Player P has won the game, and
// false otherwise.
}; // end class board
The above is part of my header file for a Tic-Tac-Toe game. I am trying test the win function and confused on how to test it from a driver file:
#include <iostream>
using namespace std;
#include "Board.h"
// function main begins program execution
int main ()
{
Board a;
cout << a.win(X) << endl; // <------------------? ? ?
return 0; // indicate successful termination
} // end function main
I have tried to create a Board::Player type in main but still cannot get it to compile. Any suggestions?
In C++, you always have to think about scope, so:
cout << a.win(X) << endl;
should be:
cout << a.win(Board::X) << endl;

Resources