"Field is never used" although its (field's) constructor runs - c++

class SdlManager
{
public:
SdlManager();
~SdlManager();
};
class Application
{
SdlManager sdlManager;
Screen screen;
EventHandler eventHandler;
bool running = true;
int fps = Fps;
void Draw();
public:
Application();
void Run();
void Stop();
};
int main(int argc, char* argv[])
{
Application app;
app.Run();
return 0;
}
Hi. I'm toying with SDL using Clion and I noticed this warning which seems strange: it complains that the field sdlManager is never used, but I'm sure (even using breakpoints) that the program runs sdlManager's constructor when I instantiate an Application object inside main.
What should I do? Is it a Clion's (or whatever plugin it uses) bug?

sdlManager is constructed, but it's never used after that. That's why you're getthing the warning.
Once you'll add methods to it, and start using them, the warning will go away.
The point of that warning is to signal code that isn't used anywhere in the code, either someone forgot to use it, or it needs to be removed (after some refactoring or something).

Related

Debug Assertion Failed Expression __acrt_first_block == header

I have been trying to figure out why this is happening and maybe it is just due to inexperience at this point but could really use some help.
When I run my code, which is compiled into a DLL using C++20, I get that a debug assertion has failed with the expression being __acrt_first_block == header.
I narrowed down where the code is failing, but the weird part is that it runs just fine when I change the Init(std::string filePath function signature to not contain the parameter. The code is below and hope someone can help.
Logger.h
#pragma once
#include "../Core.h"
#include <memory>
#include <string>
#include "spdlog/spdlog.h"
namespace Ruby
{
class RUBY_API Logger
{
public:
static void Init(std::string filePath);
inline static std::shared_ptr<spdlog::logger>& GetCoreLogger() { return coreLogger; }
inline static std::shared_ptr<spdlog::logger>& GetClientLogger() { return clientLogger; }
private:
static std::shared_ptr<spdlog::logger> coreLogger;
static std::shared_ptr<spdlog::logger> clientLogger;
};
}
Logger.cpp
namespace Ruby
{
std::shared_ptr<spdlog::logger> Logger::coreLogger;
std::shared_ptr<spdlog::logger> Logger::clientLogger;
void Logger::Init(std::string filePath)
{
std::string pattern{ "%^[%r][%n][%l]: %v%$" };
auto fileSink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(filePath, true);
// Setup the console and file sinks
std::vector<spdlog::sink_ptr> coreSinks;
coreSinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>());
coreSinks.push_back(fileSink);
// Bind the sinks to the core logger.
coreLogger = std::make_shared<spdlog::logger>("RUBY", begin(coreSinks), end(coreSinks));
// Set the Patterns for the sinks
coreLogger->sinks()[0]->set_pattern(pattern);
coreLogger->sinks()[1]->set_pattern(pattern);
// Tell spdlog to flush the file loggers on trace or worse message (can be changed if necessary).
coreLogger->flush_on(spdlog::level::trace);
// Set the default level of the logger
coreLogger->set_level(spdlog::level::trace);
// Do the same for the client logger
std::vector<spdlog::sink_ptr> clientSinks;
clientSinks.push_back(std::make_shared<spdlog::sinks::stdout_color_sink_mt>());
clientSinks.push_back(fileSink);
clientLogger = std::make_shared<spdlog::logger>("APP", begin(clientSinks), end(clientSinks));
clientLogger->sinks()[0]->set_pattern(pattern);
clientLogger->sinks()[1]->set_pattern(pattern);
clientLogger->flush_on(spdlog::level::trace);
clientLogger->set_level(spdlog::level::trace);
}
}
Entrypoint.h
#pragma once
#ifdef RB_PLATFORM_WINDOWS
extern Ruby::Application* Ruby::CreateApplication();
int main(int argc, char** argv)
{
Ruby::Logger::Init("../Logs/Recent_Run.txt");
RB_CORE_INFO("Initialized the logger.");
auto app = Ruby::CreateApplication();
app->Run();
delete app;
return 0;
}
#else
#error Ruby only supports windows
#endif // RB_PLATFORM_WINDOWS
For anyone else who runs into a similar problem, here is how I fixed it.
Essentially the function signature for the Init() function was the problem. The std::string parameter was causing the debug assertion to fire, my best guess as of right now was because of move semantics but that part I am still not sure on. So there are a couple of ways that I found to fix this.
Method 1:
Make the parameter a const char*. I don't quite like this approach as it then relies on C style strings and if you are trying to write a program in modern C++, this is a huge step backwards.
Method 2:
Make the parameter a const std::string&. Making it a const reference to a string prevents the move semantics (again as far as I know) and the assertion no longer fires. I prefer this fix as it keeps the program in modern C++.
I hope this helps anyone who has similar issues, and be careful with statics and move semantics.

Gtkmm 3/C++, closing the program with a button instead of the window "X"

everybody.
I am working on a gtkmm app and need some help getting a "Close" button to work. As suggested by the gtkmm documentation, I derived a class for the main window object, created some members, and left the main() function mostly for reading the glade UI file, instantiating the form and starting the main loop.
There are 3 files, named conveniently for explanation: Declarations.h, Declarations.cpp, Program.cpp
In "Declarations.h" I have the class inherited from the Gtk Window:
#include <gtkmm.h>
class MainWindowClass : public Gtk::ApplicationWindow
{
protected:
Gtk::Button *button_close;
// other buttons here
protected:
void on_button_close_clicked();
// other callback functions here
public:
MainWindowClass(BaseObjectType *cobject, const Glib::RefPtr<Gtk::Builder> &refGlade); // Constructor
// Destructor, other public members
};
In "Declarations.cpp" I have the implementations:
#include "Declarations.h"
using namespace Gtk;
// Implementing the constructor
MainWindowClass::MainWindowClass(BaseObjectType *cobject, const Glib::RefPtr<Gtk::Builder> &refGlade) :
Gtk::Window(cobject), builder(refGlade)
{
builder->get_widget("button_close", button_close);
// Getting other widgets from the glade file
button_close->signal_clicked().connect(sigc::mem_fun(*this, &MainWindowClass::on_button_close_clicked));
// Connecting other callback functions here
}
// Implementing the callback for the "Close" button, ** PROBLEM IS HERE **
void MainWindowClass::on_button_close_clicked()
{
//gtk_main_quit(); Apparently GTK+/C only, compiler doesn't complain but causes a segfault when clicking the button
//Gtk::Application::quit(); Won't compile
}
The Program.cpp reads the UI from a file and starts the main program loop:
#include <gtkmm.h>
#include "Declarations.h"
int main(int argc, char *argv[])
{
auto app = Gtk::Application::create(argc, argv, "Damn this close button");
Glib::RefPtr<Gtk::Builder> builder = Gtk::Builder::create_from_file("Program_UI.glade");
MainWindowClass our_main_window;
return app->run(our_main_window);
}
I am omitting some non-relevant code (of other objects and callbacks) because they work, it is the close procedure that is causing me trouble, though closing the app with "X" works.
I have also thought about trying to call a quit() or destroy() function (if they exist) of "app", but then the callback function doesn't know "app" exists.
What do you guys suggest?
Thanks a lot.
** Edit: fixed this using FormMain::hide(), which is inherited from GtkWindow.
I thought the static procedure Gtk::Main::hide() would do it, but the compiler says that hide() is not a member of Gtk::Main...
Well, moving forward one step at a time.
Used FormMain::hide() (inherited from GtkWindow). The static procedure Gtk::Main::hide() was not being recognized by the compiler.

How does initialization of static (global) objects happen

I am trying to figure out exactly how constructors for global objects are called. I understand that they are called before anything in a translation unit is used, and I am fine with that. I am trying to find out how in Linux and Windows (x86 and x64) this is accomplished.
I seem to remember that Windows (x86) used a linked list for construction and destruction, but I am having trouble finding any resources on this matter.
I have found the following material on related topics, but nothing seems to cover exactly what I am looking for.
http://blogs.msdn.com/b/freik/archive/2005/03/17/398200.aspx
http://msdn.microsoft.com/en-us/library/9b372w95.aspx
http://msdn.microsoft.com/en-us/library/7kcdt6fy.aspx
And the PE file format document.
Could anyone point me in the correct direction to find this information?
Just in case your failing to understand I have code here to demonstrate.
SourceA.cpp
#include "stdafx.h"
extern bool DoFunctionB();
class MyClassA {
protected:
bool bIsInitialized;
bool bIsBInitialized;
public:
MyClassA () : bIsInitialized(true) {
bIsBInitialized = DoFunctionB();
}
bool IsInitialized() {
return bIsInitialized;
}
};
static MyClassA MyClassGlobal;
bool DoFunctionA() {
return MyClassGlobal.IsInitialized();
}
SourceB.cpp
#include "stdafx.h"
extern bool DoFunctionA();
class MyClassB {
protected:
bool bIsInitialized;
bool bIsAInitialized;
public:
MyClassB () : bIsInitialized(true) {
bIsAInitialized = DoFunctionA();
}
bool IsInitialized() {
return bIsInitialized;
}
};
static MyClassB MyClassGlobal;
bool DoFunctionB() {
return MyClassGlobal.IsInitialized();
}
Main.cpp
#include "stdafx.h"
extern bool DoFunctionA();
extern bool DoFunctionB();
int _tmain(int argc, _TCHAR* argv[])
{
bool a = DoFunctionA();
bool b = DoFunctionB();
return 0;
}
Add these to a new windows console app. Place breakpoints in the constructors, and in the DoFunctionX() code. Hit F11 and step through it. You will see that whichever global initializer gets called first will use the DoFunction in the other cpp file before the static object in that file gets initialized.
Regardless of what you think the standard may be. This is what compilers do. And its a hazard that you have to be concerned with.
And if you step up the stack 2 steps when your in the constructor you will see the list of pointers that I've already told you about.
Happy Coding.
You are wrong to think that global constructors must be run before the object is used. I've fixed many a bug based on this assumption and it simply is not true. Not for gcc, and not for MSVC, abd certainly not for XCode.
You can specify an attribute((init_priority(X))) in gcc to force the order,
or #pragma init_seg({ compiler | lib | user | "section-name" [, func-name]} ) for msvc.
When working with XCode, the initialization code is run in the order that the object files are passed to the linker.
I dont think there is a standard, and if there is then very few people are following it. Its up to the tools creator to decide how they want to keep track of whats getting initialized and when.

Suppress qDebug when using QTestLib

I am adding unit tests to project in Qt and am looking to use QTestLib. I have set up the tests and they are running fine.
The issue is that in the project we have overridden qDebug() to output to our own log file. This works great when running the app, the problem is that when I am testing the classes, it will sometimes start logging, which is then sent to the output window. The result is a complete disaster that is next to impossible to read as our logs get mixed in with the QTest output.
I am wondering if there is a way to suppress the qDebug() output, or at least move it somewhere else. I have tried adding #define QT_NO_DEBUG_OUTPUT and also using qInstallMsgHandler(messageOutput); to redirect or prevent the output, but neither had any effect.
The solution given by #Kuba works in some cases, but not when used in conjunction with QTest::qExec(&test,argc,argv) in the main method to run a number of tests. In that case the only way to disable the qDebug() output (that I found) is for each of the test classes in their void initTestCase() slot to register a new message handler.
For example
void noMessageOutput(QtMsgType, const char *)
{}
int main(int argc,char* argv[])
{
qInstallMsgHandler(noMessageOutput);
tst_Class1 t1;
tst_Class2 t2;
QTest::qExec(&t1,argc,argv);
QTest::qExec(&t2,argc,argv);
}
Will show the debug output tst_Class1, Class1, tst_Class2, and Class2. To prevent this you must explicitly disable the output in each of the test classes
class tst_Class1
{
//class stuff
private slots:
void initTestCase();
//test cases
};
void tst_Class1::initTestCase()
{
qInstallMsgHandler(noMessageOutput);
}
class tst_Class2
{
//class stuff
private slots:
void initTestCase();
//test cases
};
void tst_Class2::initTestCase()
{
qInstallMsgHandler(noMessageOutput);
}
If you wish to see the debug output from a subset of the classes the remove the qInstallMsgHandler() line and it will come through.
The QT_NO_DEBUG_OUTPUT define must go into your project files or makefiles and must be present for every file you compile. You must then recompile your application (not Qt itself of course). This macro's presence on compiler's command line guarantees that the first time QDebug header is included by any code, the qDebug will be redefined to a no-op. That's what this macro does: it disables qDebug if it is present when the <QtCore/qdebug.h> header gets included -- whether directly by you or indirectly by other headers.
Using qInstallMsgHandler certainly works at suppressing debug output.
Below is a self-contained example.
#if 0
// Enabling this section disables all debug output from non-Qt code.
#define QT_NO_DEBUG_OUTPUT
#endif
#include <QtCore/QDebug>
void noMessageOutput(QtMsgType, const char *)
{}
int main(int argc, char *argv[])
{
qDebug() << "I'm shown";
qInstallMsgHandler(noMessageOutput);
qDebug() << "I'm hidden";
}

How can I perform pre-main initialization in C/C++ with avr-gcc?

In order to ensure that some initialization code runs before main (using Arduino/avr-gcc) I have code such as the following:
class Init {
public:
Init() { initialize(); }
};
Init init;
Ideally I'd like to be able to simply write:
initialize();
but this doesn't compile...
Is there a less verbose way to achieve the same effect?
Note: the code is part of an Arduino sketch so the main function is automatically generated and cannot be modified (for example to call initialize before any other code).
Update: ideally the initialization would be performed in the setup function, but in this case there is other code depending on it which occurs before main.
You can use GCC's constructor attribute to ensure that it gets called before main():
void Init(void) __attribute__((constructor));
void Init(void) { /* code */ } // This will always run before main()
You can make the above very slightly shorter by giving "initialize" a return type, and using that to initialize a global variable:
int initialize();
int dummy = initialize();
However, you need to be careful with this, the standard does not guarantee that the above initialization (or the one for your init object) takes place before main is run (3.6.2/3):
It is implementation-defined whether or not the dynamic initialization (8.5, 9.4, 12.1, 12.6.1) of an object of namespace scope is done before the first statement of main.
The only thing that is guaranteed is that the initialization will take place before 'dummy' is ever used.
A more intrusive option (if it's possible) might be to use "-D main=avr_main" in your makefile. You could then add your own main as follows:
// Add a declaration for the main declared by the avr compiler.
int avr_main (int argc, const char * argv[]); // Needs to match exactly
#undef main
int main (int argc, const char * argv[])
{
initialize ();
return avr_main (argc, argv);
}
At least here you're guaranteed that the initialization will take place when you expect.
Here's a somewhat evil method of achieving this:
#include <stdio.h>
static int bar = 0;
int __real_main(int argc, char **argv);
int __wrap_main(int argc, char **argv)
{
bar = 1;
return __real_main(argc, argv);
}
int main(int argc, char **argv)
{
printf("bar %d\n",bar);
return 0;
}
Add the following to the linker flags: --wrap main
eg.
gcc -Xlinker --wrap -Xlinker main a.c
The linker will replace all calls to main with calls to __wrap_main, see the ld man page on --wrap
Your solution in simple and clean. What you can additionally do is to put your code in anonymous namespace. I don't see any need to make it better than that :)
If you are using the Arduino environment, is there any reason you can't place it in the setup method?
Of course, this is after the Arduino-specific hardware setup, so if you have such low-level stuff that it really has to go before main, then you need some constructor magic.
UPDATE:
Ok, if it has to be done before the main I think the only way is to use a constructor like you already do.
You can always make a preprocessor macro of it:
#define RUN_EARLY(code) \
namespace { \
class Init { \
Init() { code; } \
}; \
Init init; \
}
Now this should work:
RUN_EARLY(initialize())
But it's not really making things shorter, just moving the verbose code around.
You can use the ".init*" sections to add C code to be run before main() (and even the C runtime). These sections are linked into the executable at the end and called up at specific time during program initialization. You can get the list here:
http://www.nongnu.org/avr-libc/user-manual/mem_sections.html
.init1 for example is weakly bound to __init(), so if you define __init(), it will be linked and called first thing. However, the stack hasn't been setup, so you have to be careful in what you do (only use register8_t variable, not call any functions).
Use static members of classes. They are initialized before entering to main. The disadvantage is that you can't control the order of the initialization of the static class members.
Here is your example transformed:
class Init {
private:
// Made the constructor private, so to avoid calling it in other situation
// than for the initialization of the static member.
Init() { initialize(); }
private:
static Init INIT;
};
Init Init::INIT;
Sure, you put this in one of your your header files, say preinit.h:
class Init { public: Init() { initialize(); } }; Init init;
and then, in one of your compilation units, put:
void initialize(void) {
// weave your magic here.
}
#include "preinit.h"
I know that's a kludge but I'm not aware of any portable way to do pre-main initialization without using a class constructor executed at file scope.
You should also be careful of including more than one of these initialization functions since I don't believe C++ dictates the order - it could be random.
I'm not sure of this "sketch" of which you speak but would it be possible to transform the main compilation unit with a script before having it passed to the compiler, something like:
awk '{print;if (substr($0,0,11) == "int main (") {print "initialize();"};}'
You can see how this would affect your program because:
echo '#include <stdio.h>
int main (void) {
int x = 1;
return 0;
}' | awk '{
print;
if (substr($0,0,11) == "int main (") {
print " initialize();"
}
}'
generates the following with the initialize() call added:
#include <stdio.h>
int main (void) {
initialize();
int x = 1;
return 0;
}
It may be that you can't post-process the generated file in which case you should ignore that final option, but that's what I'd be looking at first.
There is how I perform pre-main coding.
There are sever init sections executed before main, refers to http://www.nongnu.org/avr-libc/user-manual/mem_sections.html initN sections.
Anyhow, this only works on -O0 optimization for some reason. I still try to find out which option "optimized" my pre-main assembly code away.
static void
__attribute__ ((naked))
__attribute__ ((section (".init8"))) /* run this right before main */
__attribute__ ((unused)) /* Kill the unused function warning */
stack_init(void) {assembly stuff}
Update, it turns out I claimed this function is unused, leading to optimize the routine away. I was intended to kill function unused warning. It is fixed to used used attribute instead.