Static C++ Variable Apple Mach-o Linker issue - c++

I am working on an Ogre project and I am getting some issues with Xcode.
Whenever I make the scene manager pointer static, the program does not compile and I get the following error:
Undefined symbols for architecture x86_64:
"OgreInit::sceneManager", referenced from:
OgreInit::initOgre() in OgreInit.o
OgreInit::initScene() in OgreInit.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
Here is my OgreInit.cpp
#include <iostream>
#include <exception>
#include <string>
#include "OGRE/Ogre.h"
#include "OGRE/OgreException.h"
#include "OGRE/OgreRoot.h"
#include "OGRE/OgreResourceManager.h"
#include "OGRE/OgreMath.h"
#include "MainLoop.h"
#include "WorkingDirectory.h"
#include "OgreInit.h"
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include "macUtils.h"
#endif
OgreInit::OgreInit()
{
mainLoop = new MainLoop();
mainLoop->startLoop();
initOgre();
initScene();
}
void OgreInit::initOgre()
{
root = new Ogre::Root(WorkingDirectory::getResourcesDirectory() + "plugins.cfg", WorkingDirectory::getResourcesDirectory() + "window.cfg", "");
root->showConfigDialog();
window = root->initialise(true);
sceneManager = root->createSceneManager(Ogre::ST_GENERIC);
camera = sceneManager->createCamera("mainCamera");
camera->setNearClipDistance(0.1);
camera->setFarClipDistance(300);
camera->setPosition(0, 0, 80);
//camera->lookAt(Ogre::Vector3::ZERO);
cameraNode = sceneManager->getRootSceneNode()->createChildSceneNode();
cameraNode->attachObject(camera);
viewport = window->addViewport(camera);
viewport->setClearEveryFrame(true);
viewport->setAutoUpdated(true);
viewport->setBackgroundColour(Ogre::ColourValue(1, 0, 1));
Ogre::ResourceGroupManager::getSingleton().addResourceLocation(WorkingDirectory::getModelDirectory(), "FileSystem");
Ogre::ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
}
void OgreInit::initScene()
{
sceneManager->setAmbientLight(Ogre::ColourValue(0.5f, 0.5f, 0.5f));
Ogre::Entity *ogreHead = sceneManager->createEntity("Head", "ogrehead.mesh");
Ogre::SceneNode *headNode = sceneManager->getRootSceneNode()->createChildSceneNode("HeadNode");
headNode->attachObject(ogreHead);
headNode->rotate(*new Ogre::Vector3(0, 1, 0), (Ogre::Radian)Ogre::Math::DegreesToRadians(90));
Ogre::Light *light = sceneManager->createLight("MainLight");
light->setPosition(20.0f, 80.0f, 50.0f);
}
//init resources before scene :! and translate before attaching
OgreInit::~OgreInit()
{
}
And of course the header:
#ifndef __OgreTest__OgreInit__
#define __OgreTest__OgreInit__
#include <iostream>
#include <string>
#include <memory>
#include "OGRE/Ogre.h"
#include "MainLoop.h"
class OgreInit
{
public:
OgreInit();
~OgreInit();
private:
void initOgre();
void initScene();
MainLoop *mainLoop;
Ogre::Root *root;
Ogre::RenderWindow *window;
static Ogre::SceneManager *sceneManager;
Ogre::Viewport *viewport;
Ogre::Camera *camera;
Ogre::SceneNode *cameraNode;
};
#endif /* defined(__OgreTest__OgreInit__) */
I have seen this issue on Stackoverflow quite often, but usually it happened because some required libraries were not included. I don't think that is the issue here because I am not getting any errors if I change: static Ogre::SceneManager *sceneManager; to: Ogre::SceneManager *sceneManager;
Thanks in advance.

As well as declaring it in your header file, you need to actually define the sceneManager in your implementation file:
...
#if OGRE_PLATFORM == OGRE_PLATFORM_APPLE
#include "macUtils.h"
#endif
Ogre::SceneManager *OgreInit::sceneManager = 0;
OgreInit::OgreInit()
{
...

Related

LLVM 8 and later ORC JIT problems with math library

Since LLVM 8 (including current LLVM trunk, aka LLVM 9) I run into a problem when using the ORC JIT ExecutionEngine with functions which contain a call to the standard math library.
The JIT compiler is able to find the symbol for the function but fails to get the address for it in case the function makes a call to the math library.
I attach a simple exploit that shows the problem. The program test.cc reads in an IR file which contains a single function in LLVM's Intermediate Representation:
The function takes a single argument, a floating point number, and returns in case of
"func_works.ll" the argument itself, and in case of
"func_cos_fails.ll" the cosine of the argument.
I didn't implement the choice between the two files at runtime, so the program needs to be rebuilt when switching to the other case.
The program uses the standard KaleidoscopeJIT.h that comes with LLVM (except that I had to expose the Datalayout).
If you build the program with the "func_works.ll" and run it, the program succeeds with:
symbol found!
address found!
If you build the program with the "func_cos_fails.ll" and run it, the program fails with:
symbol found!
Failure value returned from cantFail wrapped call
UNREACHABLE executed at install/llvm-8.0-x86-debug/include/llvm/Support/Error.h:732!
This happens with LLVM 8 release and the current LLVM trunk.
Does anyone see what's going on?
This test was run on an x86 Linux Ubuntu system with LLVM configured with
cmake -G "Unix Makefiles" \
-DBUILD_SHARED_LIBS="ON" \
-DLLVM_ENABLE_RTTI="ON" \
-DLLVM_ENABLE_ZLIB="OFF" \
-DLLVM_ENABLE_TERMINFO="OFF" \
-DCMAKE_BUILD_TYPE="Debug" \
-DCMAKE_INSTALL_PREFIX=$CMAKE_INSTALL_PREFIX \
-DLLVM_TARGETS_TO_BUILD="X86" \
$SRC
test.cc:
#include "KaleidoscopeJIT.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/ExecutionEngine/ObjectCache.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IRReader/IRReader.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Support/InitLLVM.h"
#include <iostream>
using namespace llvm;
using namespace llvm::orc;
int main(int argc, char **argv) {
InitLLVM X(argc, argv);
EnableDebugBuffering = true;
LLVMContext Context;
InitializeNativeTarget();
InitializeNativeTargetAsmPrinter();
InitializeNativeTargetAsmParser();
cl::ParseCommandLineOptions(argc, argv, "Kaleidoscope example program\n");
SMDiagnostic Err;
std::unique_ptr<llvm::Module> M = parseIRFile( "func_cos_fails.ll" , Err, Context, false);
//std::unique_ptr<llvm::Module> M = parseIRFile( "func_works.ll" , Err, Context, false);
if (!M) {
Err.print("IR parsing failed: ", errs());
return 0;
}
std::unique_ptr<KaleidoscopeJIT> TheJIT;
TheJIT = llvm::make_unique<KaleidoscopeJIT>();
auto H = TheJIT->addModule(std::move(M));
std::string MangledName;
llvm::raw_string_ostream MangledNameStream(MangledName);
llvm::Mangler::getNameWithPrefix(MangledNameStream, "func_ir" , TheJIT->getDL() );
if (auto Sym = TheJIT->findSymbol(MangledNameStream.str()))
{
std::cout << "symbol found!\n";
void* fptr = (void *)cantFail(Sym.getAddress());
std::cout << "address found!\n";
}
else
{
std::cout << "symbol not found!\n";
}
return 0;
}
func_cos_fails.ll:
source_filename = "module"
target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
declare float #cosf(float)
define float #func_ir(float %arg0) {
entrypoint:
%0 = call float #cosf(float %arg0)
ret float %0
}
func_works.ll:
source_filename = "module"
target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"
define float #func_ir(float %arg0) {
entrypoint:
ret float %arg0
}
KaleidoscopeJIT.h:
#ifndef LLVM_EXECUTIONENGINE_ORC_KALEIDOSCOPEJIT_H
#define LLVM_EXECUTIONENGINE_ORC_KALEIDOSCOPEJIT_H
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/iterator_range.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/JITSymbol.h"
#include "llvm/ExecutionEngine/Orc/CompileUtils.h"
#include "llvm/ExecutionEngine/Orc/IRCompileLayer.h"
#include "llvm/ExecutionEngine/Orc/LambdaResolver.h"
#include "llvm/ExecutionEngine/Orc/RTDyldObjectLinkingLayer.h"
#include "llvm/ExecutionEngine/RTDyldMemoryManager.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/Mangler.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Target/TargetMachine.h"
#include <algorithm>
#include <map>
#include <memory>
#include <string>
#include <vector>
namespace llvm {
namespace orc {
class KaleidoscopeJIT {
public:
using ObjLayerT = LegacyRTDyldObjectLinkingLayer;
using CompileLayerT = LegacyIRCompileLayer<ObjLayerT, SimpleCompiler>;
KaleidoscopeJIT()
: Resolver(createLegacyLookupResolver(
ES,
[this](const std::string &Name) {
return ObjectLayer.findSymbol(Name, true);
},
[](Error Err) { cantFail(std::move(Err), "lookupFlags failed"); })),
TM(EngineBuilder().selectTarget()), DL(TM->createDataLayout()),
ObjectLayer(ES,
[this](VModuleKey) {
return ObjLayerT::Resources{
std::make_shared<SectionMemoryManager>(), Resolver};
}),
CompileLayer(ObjectLayer, SimpleCompiler(*TM)) {
llvm::sys::DynamicLibrary::LoadLibraryPermanently(nullptr);
}
TargetMachine &getTargetMachine() { return *TM; }
VModuleKey addModule(std::unique_ptr<Module> M) {
auto K = ES.allocateVModule();
cantFail(CompileLayer.addModule(K, std::move(M)));
ModuleKeys.push_back(K);
return K;
}
void removeModule(VModuleKey K) {
ModuleKeys.erase(find(ModuleKeys, K));
cantFail(CompileLayer.removeModule(K));
}
JITSymbol findSymbol(const std::string Name) {
return findMangledSymbol(mangle(Name));
}
const DataLayout& getDL() const {
return DL;
}
private:
std::string mangle(const std::string &Name) {
std::string MangledName;
{
raw_string_ostream MangledNameStream(MangledName);
Mangler::getNameWithPrefix(MangledNameStream, Name, DL);
}
return MangledName;
}
JITSymbol findMangledSymbol(const std::string &Name) {
#ifdef _WIN32
// The symbol lookup of ObjectLinkingLayer uses the SymbolRef::SF_Exported
// flag to decide whether a symbol will be visible or not, when we call
// IRCompileLayer::findSymbolIn with ExportedSymbolsOnly set to true.
//
// But for Windows COFF objects, this flag is currently never set.
// For a potential solution see: https://reviews.llvm.org/rL258665
// For now, we allow non-exported symbols on Windows as a workaround.
const bool ExportedSymbolsOnly = false;
#else
const bool ExportedSymbolsOnly = true;
#endif
// Search modules in reverse order: from last added to first added.
// This is the opposite of the usual search order for dlsym, but makes more
// sense in a REPL where we want to bind to the newest available definition.
for (auto H : make_range(ModuleKeys.rbegin(), ModuleKeys.rend()))
if (auto Sym = CompileLayer.findSymbolIn(H, Name, ExportedSymbolsOnly))
return Sym;
// If we can't find the symbol in the JIT, try looking in the host process.
if (auto SymAddr = RTDyldMemoryManager::getSymbolAddressInProcess(Name))
return JITSymbol(SymAddr, JITSymbolFlags::Exported);
#ifdef _WIN32
// For Windows retry without "_" at beginning, as RTDyldMemoryManager uses
// GetProcAddress and standard libraries like msvcrt.dll use names
// with and without "_" (for example "_itoa" but "sin").
if (Name.length() > 2 && Name[0] == '_')
if (auto SymAddr =
RTDyldMemoryManager::getSymbolAddressInProcess(Name.substr(1)))
return JITSymbol(SymAddr, JITSymbolFlags::Exported);
#endif
return nullptr;
}
ExecutionSession ES;
std::shared_ptr<SymbolResolver> Resolver;
std::unique_ptr<TargetMachine> TM;
const DataLayout DL;
ObjLayerT ObjectLayer;
CompileLayerT CompileLayer;
std::vector<VModuleKey> ModuleKeys;
};
} // end namespace orc
} // end namespace llvm
#endif // LLVM_EXECUTIONENGINE_ORC_KALEIDOSCOPEJIT_H
for convenience I provide a Makefile:
LLVM_CONFIG = ${LLVM_INSTALL_PATH}
LLVM_CXXFLAGS = $(shell $(LLVM_CONFIG) --cxxflags)
LLVM_LDFLAGS = $(shell $(LLVM_CONFIG) --ldflags)
LLVM_LIBS = $(shell $(LLVM_CONFIG) --libs)
all: test
test.o: test.cc KaleidoscopeJIT.h
g++ -c -o $# $< $(LLVM_CXXFLAGS)
test: test.o
g++ -o $# $< $(LLVM_LDFLAGS) $(LLVM_LIBS)
clean:
rm -f *.o
rm -f test
I believe the solution to this (for llvm 7 and 8 anyway) was found here:
https://stackoverflow.com/a/56862433/2310373
Namely, replace:
[this](const std::string &Name) {
return ObjectLayer.findSymbol(Name, true);
},
With something like
[this](const std::string &Name) {
auto FoundSymbol = ObjectLayer.findSymbol(Name, true);
if (!FoundSymbol) {
if (auto SymAddr = RTDyldMemoryManager::getSymbolAddressInProcess(Name))
return JITSymbol(SymAddr, JITSymbolFlags::Exported);
}
return FoundSymbol;
},

unresolved external symbol class Matrix4*4 point coud library

I'm trying to load a pcd file using pcl library, I do and show it using cloud viewer but I'm trying to use PCLVisualizer.
When I use addPointCloud function I have an error:
Severity Code Description Project File Line Suppression State
Error LNK2019 unresolved external symbol "public: static class vtkMatrix4x4 * __cdecl vtkMatrix4x4::New(void)" (?New#vtkMatrix4x4##SAPEAV1#XZ) referenced in function "public: static class vtkSmartPointer __cdecl vtkSmartPointer::New(void)" (?New#?$vtkSmartPointer#VvtkMatrix4x4####SA?AV1#XZ) SamplePCL C:\Users\Nima_S_H\Documents\Visual Studio 2015\Projects\SamplePCL\SamplePCL\Source.obj 1
My codes:
#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#define _HAS_ITERATOR_DEBUGGING 0
#define _ITERATOR_DEBUG_LEVEL 0
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/pcl_visualizer.h>
void main()
{
typedef pcl::PointXYZRGB PTYPE;
pcl::PointCloud<PTYPE>::Ptr myCloudPtr(new pcl::PointCloud<PTYPE>);
if (pcl::io::loadPCDFile("e:/myCloudASCII.pcd", *myCloudPtr) == -1)
{
PCL_ERROR("Could not read PCD file.");
return;
}
pcl::visualization::PCLVisualizer viz;
viz.addPointCloud(myCloudPtr);
viz.spin();
}
this works for me.
Edit: actually it works even without the spinOnce . just use spin..
#define _CRT_SECURE_NO_DEPRECATE
#define _CRT_SECURE_NO_WARNINGS
#define _HAS_ITERATOR_DEBUGGING 0
#define _ITERATOR_DEBUG_LEVEL 0
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/pcd_io.h>
#include <pcl/visualization/pcl_visualizer.h>
int main()
{
typedef pcl::PointXYZ PTYPE;
pcl::PointCloud<PTYPE>::Ptr myCloudPtr(new pcl::PointCloud<PTYPE>);
if (pcl::io::loadPCDFile("test.pcd", *myCloudPtr) == -1)
{
PCL_ERROR("Could not read PCD file.");
return 0;
}
pcl::visualization::PCLVisualizer viz;
viz.addPointCloud(myCloudPtr);
while (!viz.wasStopped ())
{
viz.spinOnce (100);
}
return 1;
}

Why is my LLVM JIT implementation segfaulting?

I'm trying to implement a simple JIT compiler using LLVM, following along with the tutorial (http://releases.llvm.org/4.0.1/docs/tutorial/BuildingAJIT1.html), and I'm running into a segfault. I've rewritten my code in the form a minimal (albeit still kinda long) example. The example loops through the integers 0 through 9 and for each one attempts to compile a function that prints that integer, add it to a module, execute the function, and then remove the module from the JIT. This is to simulate an interactive session in which a user inputs commands such as print 0, print 1, etc.
#include <array>
#include <cstdint>
#include <iostream>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/JITSymbol.h>
#include <llvm/ExecutionEngine/Orc/CompileUtils.h>
#include <llvm/ExecutionEngine/Orc/IRCompileLayer.h>
#include <llvm/ExecutionEngine/Orc/LambdaResolver.h>
#include <llvm/ExecutionEngine/Orc/ObjectLinkingLayer.h>
#include <llvm/ExecutionEngine/SectionMemoryManager.h>
#include <llvm/ExecutionEngine/RuntimeDyld.h>
#include <llvm/IR/BasicBlock.h>
#include <llvm/IR/Constants.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/GlobalValue.h>
#include <llvm/IR/GlobalVariable.h>
#include <llvm/IR/IRBuilder.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/LegacyPassManager.h>
#include <llvm/IR/Mangler.h>
#include <llvm/IR/Module.h>
#include <llvm/IR/Type.h>
#include <llvm/IR/Value.h>
#include <llvm/IR/Verifier.h>
#include <llvm/Support/DynamicLibrary.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Support/raw_ostream.h>
#include <llvm/Target/TargetMachine.h>
#include <llvm/Transforms/Scalar.h>
#include <llvm/Transforms/Scalar/GVN.h>
#include <memory>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>
int main() {
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
auto machine = llvm::EngineBuilder().selectTarget();
llvm::orc::ObjectLinkingLayer<> linking_layer;
llvm::orc::IRCompileLayer<llvm::orc::ObjectLinkingLayer<>> compile_layer(
linking_layer, llvm::orc::SimpleCompiler(*machine)
);
llvm::LLVMContext context;
llvm::IRBuilder<> builder(context);
auto layout = machine->createDataLayout();
auto module = std::make_unique<llvm::Module>("module", context);
auto manager = std::make_unique<llvm::legacy::FunctionPassManager>(
module.get()
);
for (
auto p : {
llvm::createInstructionCombiningPass(),
llvm::createReassociatePass(), llvm::createGVNPass(),
llvm::createCFGSimplificationPass()
}
) manager->add(p);
module->setDataLayout(layout);
llvm::sys::DynamicLibrary::LoadLibraryPermanently(nullptr);
auto index = llvm::ConstantInt::get(context, llvm::APInt(8, 0));
std::vector<llvm::Constant*> indices = {index, index};
std::string func_name = "func";
for (auto i = 0; i < 10; ++i) {
auto format_str = new llvm::GlobalVariable(
*module, llvm::ArrayType::get(llvm::Type::getInt8Ty(context), 4),
true, llvm::GlobalValue::PrivateLinkage,
llvm::ConstantDataArray::getString(context, "%i\n"), "format_str"
);
format_str->setAlignment(1);
auto function = llvm::Function::Create(
llvm::FunctionType::get(
llvm::Type::getVoidTy(context), std::vector<llvm::Type*>{},
false
), llvm::Function::ExternalLinkage, func_name, module.get()
);
builder.SetInsertPoint(
llvm::BasicBlock::Create(context, "entry", function)
);
builder.CreateCall(
module->getOrInsertFunction(
"printf", llvm::FunctionType::get(
llvm::IntegerType::getInt32Ty(context),
llvm::PointerType::get(llvm::Type::getInt8Ty(context), 0),
true
)
), std::vector<llvm::Value*>{
llvm::ConstantExpr::getGetElementPtr(
nullptr, format_str, indices
), llvm::ConstantInt::get(context, llvm::APInt(32, i))
}, "call"
);
builder.CreateRetVoid();
std::string message;
llvm::raw_string_ostream message_stream(message);
if (llvm::verifyFunction(*function, &message_stream))
throw std::runtime_error(message_stream.str());
auto handle = compile_layer.addModuleSet(
std::array<std::unique_ptr<llvm::Module>, 1>{std::move(module)},
std::make_unique<llvm::SectionMemoryManager>(),
llvm::orc::createLambdaResolver(
[&](const std::string& name) {
auto symbol = compile_layer.findSymbol(name, false);
return symbol ? symbol : llvm::JITSymbol(nullptr);
}, [](const std::string& name) {
auto address = llvm::RTDyldMemoryManager::
getSymbolAddressInProcess(name);
return address ? llvm::JITSymbol(
address, llvm::JITSymbolFlags::Exported
) : llvm::JITSymbol(nullptr);
}
)
);
std::string mangled_name;
llvm::raw_string_ostream mangled_name_stream(mangled_name);
llvm::Mangler::getNameWithPrefix(
mangled_name_stream, func_name, layout
);
(
reinterpret_cast <void(*)()> (
static_cast <intptr_t> (
compile_layer.findSymbol(
mangled_name_stream.str(), true
).getAddress()
)
)
)();
compile_layer.removeModuleSet(handle);
}
}
The expected output is as follows.
0
1
2
3
4
5
6
7
8
9
Instead I get this.
0
Segmentation fault (core dumped)
According to GDB, the segfault is occuring during the call to llvm::GlobalVariable::GlobalVariable. Here's the backtrace.
#0 0x00007ffcdb8b6541 in llvm::GlobalVariable::GlobalVariable(llvm::Module&, llvm::Type*, bool, llvm::GlobalValue::LinkageTypes, llvm::Constant*, llvm::Twine const&, llvm::GlobalVariable*, llvm::GlobalValue::ThreadLocalMode, unsigned int, bool) () from /usr/lib/libLLVM-4.0.so
#1 0x000000010000698a in main () at main.cc:83
I'm using LLVM version 4.0.1 and GCC version 7.1.1 and compiling with the following command.
g++ -std=c++17 main.cc -o main -O0 -Wall -Wextra -Wno-unused-function \
-Wno-unused-value -Wno-unused-parameter -Werror -ggdb \
`llvm-config --system-libs --libs core`
I'm hoping some LLVM veteran can find my mistake. Thanks, guys!
module is initialized before the for loop:
auto module = std::make_unique<llvm::Module>("module", context);
then in the for loop:
for(...)
{
auto format_str = new llvm::GlobalVariable(*module, ...);
^~~~~~~
...
std::array<std::unique_ptr<llvm::Module>, 1>{std::move(module)},
^~~~~~~~~~~~~~~~~
}
At first iteration you access the object owned by module (ok) and then move from it. This will transfer the ownership of the managed object away from module.
At the second iteration you access the object managed by module -> crash (because it doesn't have a managed object anymore)

Error while trying to build stasm minimal

I do not have experience on C++. And I have to use stasm for face detection. I'm traying to build the minimal example. On page 4 of this tutorial is possible to know what is necessary to make it work. But I'm these two errors:
g++ -Wno-deprecated -o teste minimal.cpp `pkg-config opencv --cflags --libs` -I/home/caaarlos/workspace/StasmDesbravando/stasm
In file included from minimal.cpp:46:0:
/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/pinstart.cpp: In function ‘void stasm::CopyPoint(stasm::Shape&, const Shape&, int, int)’:
/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/pinstart.cpp:138:13: error: redefinition of ‘void stasm::CopyPoint(stasm::Shape&, const Shape&, int, int)’
static void CopyPoint( // copy a point from oldshape to shape
^
In file included from minimal.cpp:37:0:
/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/convshape.cpp:9:13: error: ‘void stasm::CopyPoint(stasm::Shape&, const Shape&, int, int)’ previously defined here
static void CopyPoint( // copy a point from oldshape to shape
This is my code:
// minimal.cpp: Display the landmarks of a face in an image.
// This demonstrates stasm_search_single.
#include <stdio.h>
#include <stdlib.h>
#include "opencv/highgui.h"
#include <opencv/cv.h>
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/stasm_lib.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/asm.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/atface.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/basedesc.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/classicdesc.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/convshape.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/err.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/eyedet.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/eyedist.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/faceroi.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/hat.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/hatdesc.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/landmarks.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/landtab_muct77.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/misc.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/pinstart.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/print.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/shape17.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/shapehacks.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/shapemod.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/startshape.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/stasm.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/stasm_landmarks.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/stasm_lib.h"
//#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/stasm_lib_ext.h"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/asm.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/classicdesc.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/convshape.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/err.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/eyedet.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/eyedist.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/faceroi.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/hat.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/hatdesc.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/landmarks.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/misc.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/pinstart.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/print.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/shape17.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/shapehacks.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/shapemod.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/startshape.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/stasm.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/stasm_lib.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/MOD_1/facedet.h"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/MOD_1/initasm.h"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/MOD_1/initasm.cpp"
#include "/home/caaarlos/Documentos/TCC/stasm4.1.0/stasm/MOD_1/facedet.cpp"
using namespace cv;
using namespace std;
int main()
{
static const char* const path = "../data/testface.jpg";
cv::Mat_<unsigned char> img(cv::imread(path, CV_LOAD_IMAGE_GRAYSCALE));
if (!img.data)
{
printf("Cannot load %s\n", path);
exit(1);
}
int foundface;
float landmarks[2 * stasm_NLANDMARKS]; // x,y coords (note the 2)
if (!stasm_search_single(&foundface, landmarks,
(const char*)img.data, img.cols, img.rows, path, "../data"))
{
printf("Error in stasm_search_single: %s\n", stasm_lasterr());
exit(1);
}
if (!foundface)
printf("No face found in %s\n", path);
else
{
// draw the landmarks on the image as white dots (image is monochrome)
stasm_force_points_into_image(landmarks, img.cols, img.rows);
for (int i = 0; i < stasm_NLANDMARKS; i++)
img(cvRound(landmarks[i*2+1]), cvRound(landmarks[i*2])) = 255;
}
cv::imwrite("minimal.bmp", img);
cv::imshow("stasm minimal", img);
cv::waitKey();
return 0;
}
I'm compiling my code in thi way:
g++ -Wno-deprecated -o teste minimal.cpp `pkg-config opencv --cflags --libs` -I/home/caaarlos/workspace/StasmDesbravando/stasm
What am I doing wrong? Can someone help me?
Thanks.
I've found a solution for this problem. If somebody has a problem like mine, you should enter on this site and use the CMakeList.txt and CMake to build Stasm. If you get any error you can try the intructions provides o the readme.

Controlling Windows Media Player 12 with Qt / ActiveQt

I am trying to embed a movie in a Qt (4.7.1) widget using ActiveQt:
VideoManager2.h:
#ifndef VIDEOMANAGER2_H_
#define VIDEOMANAGER2_H_
#include <QtCore/QtCore>
#include <QtGui/QtGui>
#include "qaxwidget.h"
class VideoManager2: public QWidget{
Q_OBJECT
//Q_ENUMS(ReadyStateConstants);
enum PlayStateConstants { Stopped = 0, Paused = 1, Playing = 2 };
enum ReadyStateConstants { Uninitialized = 0, Loading = 1, Interactive = 3, Complete = 4 };
QAxWidget *wmp;
private slots:
void onPlayStateChange(int a, int b);
void onReadyStateChange(ReadyStateConstants readyState);
public:
VideoManager2();
};
#endif /* VIDEOMANAGER2_H_ */
VideoManager2.cpp:
#include <QtCore/QtCore>
#include <QtGui/QtGui>
#include <InitGuid.h>
#include "VideoManager2.h"
#include "wmp.h"
#include "qaxobject.h"
VideoManager2::VideoManager2() {
wmp = new QAxWidget(this);
wmp->setControl("{6BF52A52-394A-11D3-B153-00C04F79FAA6}");
wmp->setProperty("ShowControls", false);
wmp->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
wmp->setProperty("URL", "C:/Users/qxf3567/Downloads/demoMedia/movie/earth.avi");
qDebug("Version Info: %s", qPrintable(wmp->property("versionInfo").toString()));
qDebug("Playing: %s", qPrintable(wmp->property("URL").toString()));
qDebug("State: %s", qPrintable(wmp->property("playState").toString()));
QAxObject* currentMedia= wmp->querySubObject("currentMedia");
IWMPMedia *media;
currentMedia->queryInterface(QUuid(__uuidof(IWMPMedia)), (void **)&media);
{
BSTR durationStr;
media->get_durationString(&durationStr);
QString convertedBSTR((QChar*) durationStr, wcslen(durationStr));
qDebug("Duration: %s", qPrintable(QString(convertedBSTR)));
}
}
void VideoManager2::onPlayStateChange(int a, int b){
}
void VideoManager2::onReadyStateChange(ReadyStateConstants readyState){
}
main.cpp:
...
QScrollArea *movieWidget = new QScrollArea(groupBox_2);
VideoManager2 vm;
ui->movieWidget->setWidget(&vm);
...
Output:
Version Info: 12.0.7601.18741
Playing: C:\Users\qxf3567\Downloads\demoMedia\movie\earth.avi
State: 9
Duration: 00:00
I can get the Version number of WMPlayer, but the movie to be played is displayed as 0 length. What could be the problem here? It's as if it doensn't find the file in the first place?!