OS: Win7
IDE: Visual Studio 2010
Boost Version: 1.47
I'm new to Boost and what I'm trying is very simple. I've created a single thread in a header file and tried putting it to sleep. But I can't get it working. Here is the code and compilation errors
main.h -
#pragma once
#include <conio.h>
#include <boost\thread.hpp>
boost::posix_time::seconds workTime ( 120 );
boost::this_thread::sleep ( workTime );
main.cpp
#include "main.h"
void main ( void ) {
_getch();
};
Output -
error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
error C2365: 'boost::this_thread::sleep' : redefinition; previous definition was 'function'
error C2491: 'boost::this_thread::sleep' : definition of dllimport data not allowed
error C2482: 'boost::this_thread::sleep' : dynamic initialization of 'thread' data not allowed
Using the following code now, all in main.cpp:
#include <boost\thread.hpp>
#include <conio.h>
void thread_func()
{
boost::posix_time::seconds workTime ( 120 );
boost::this_thread::sleep ( workTime );
}
int main(int argc, char* argv[])
{
boost::thread t(thread_func);
_getch();
}
Receiving the following errors:
1>LIBCMTD.lib(dbgheap.obj) : error LNK2005: __heap_alloc already defined in LIBCMT.lib(malloc.obj)
1>LIBCMTD.lib(dbgheap.obj) : error LNK2005: __recalloc already defined in LIBCMT.lib(recalloc.obj)
1>LIBCMTD.lib(dbgheap.obj) : error LNK2005: __msize already defined in LIBCMT.lib(msize.obj)
1>LIBCMTD.lib(dbghook.obj) : error LNK2005: __crt_debugger_hook already defined in LIBCMT.lib(dbghook.obj)
1>LIBCMTD.lib(isctype.obj) : error LNK2005: __isctype_l already defined in LIBCMT.lib(isctype.obj)
1>LIBCMTD.lib(isctype.obj) : error LNK2005: __isctype already defined in LIBCMT.lib(isctype.obj)
1>LINK : warning LNK4098: defaultlib 'LIBCMTD' conflicts with use of other libs; use /NODEFAULTLIB:library
1>fatal error LNK1169: one or more multiply defined symbols found
You are calling boost::this_thread::sleep ( workTime ) outside of any control flow. You should do something like:
void thread_func()
{
boost::posix_time::seconds workTime ( 120 );
boost::this_thread::sleep ( workTime );
}
int main(int argc, char* argv[])
{
boost::thread t(thread_func);
_getch();
}
Related
I'm using Visual C++ and manually attempting to load OpenGL extensions. However, for some reason defining the pointers from the Khronos Groups' provided headers leads to linker errors and as such I never get the change to even define these functions within my OpenGL context. Below I have included a simplified version of my code and it's structure that causes the same issue.
//Test.cpp
#include "MyGL.h"
#include <iostream>
int main()
{
std::cout << "Hello World!\n";
}
//MyGL.h
#pragma once
#include "MyGLOpenGL.h"
//MyGL.cpp
#include "MyGL.h"
//MyGLOpenGL.h
#pragma once
#include <windows.h> // Windows functions
#include <GL/gl.h> // Provided w/ Compiler
#include "GL/glext.h" // Put out by Khronos Group
#include "GL/wglext.h" // Put out by Khronos Group
#pragma comment(lib, "opengl32.lib") // Provided w/ Compiler
#ifndef GL_OPENGL
#define GL_OPENGL
void glInitPointers(); // Defines pointers to opengl functions
void* glGetAnyProcAddress(const char* name); // Gets a pointer to any OpenGL function
extern PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB;
extern PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB;
#endif
//MyGLOpenGL.cpp
#include "MyGLOpenGL.h"
void glInitPointers() {
wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)glGetAnyProcAddress("wglChoosePixelFormatARB"); //load function
wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)glGetAnyProcAddress("wglCreateContextAttribsARB"); //load function
return;
}
void* glGetAnyProcAddress(const char* name) {
void *pointer = (void *)wglGetProcAddress(name);
if (pointer == 0 || (pointer == (void*)0x1) || (pointer == (void*)0x2) || (pointer == (void*)0x3) || (pointer == (void*)-1)) {
HMODULE module = LoadLibraryW(L"opengl32.dll");
pointer = (void *)GetProcAddress(module, name);
}
return pointer;
};
Compiling this gives me the following linker errors:
1>MyGLOpenGL.obj : error LNK2001: unresolved external symbol "int (__stdcall* wglChoosePixelFormatARB)(struct HDC__ *,int const *,float const *,unsigned int,int *,unsigned int *)" (?wglChoosePixelFormatARB##3P6GHPAUHDC__##PBHPBMIPAHPAI#ZA)
1>MyGLOpenGL.obj : error LNK2001: unresolved external symbol "struct HGLRC__ * (__stdcall* wglCreateContextAttribsARB)(struct HDC__ *,struct HGLRC__ *,int const *)" (?wglCreateContextAttribsARB##3P6GPAUHGLRC__##PAUHDC__##PAU1#PBH#ZA)
1>G:\Development\Test\Debug\Test.exe : fatal error LNK1120: 2 unresolved externals
As the issue was unresolved external symbols, I tried removing the extern keyword to arrive at getting these two errors instead:
1>MyGLOpenGL.obj :error LNK2005: "int (__stdcall* wglChoosePixelFormatARB)(struct HDC__ *,int const *,float const *,unsigned int,int *,unsigned int *)" (?wglChoosePixelFormatARB##3P6GHPAUHDC__##PBHPBMIPAHPAI#ZA) already defined in MyGL.obj
1>MyGLOpenGL.obj : error LNK2005: "struct HGLRC__ * (__stdcall* wglCreateContextAttribsARB)(struct HDC__ *,struct HGLRC__ *,int const *)" (?wglCreateContextAttribsARB##3P6GPAUHGLRC__##PAUHDC__##PAU1#PBH#ZA) already defined in MyGL.obj
1>Test.obj : error LNK2005: "int (__stdcall* wglChoosePixelFormatARB)(struct HDC__ *,int const *,float const *,unsigned int,int *,unsigned int *)" (?wglChoosePixelFormatARB##3P6GHPAUHDC__##PBHPBMIPAHPAI#ZA) already defined in MyGL.obj
1>Test.obj : error LNK2005: "struct HGLRC__ * (__stdcall* wglCreateContextAttribsARB)(struct HDC__ *,struct HGLRC__ *,int const *)" (?wglCreateContextAttribsARB##3P6GPAUHGLRC__##PAUHDC__##PAU1#PBH#ZA) already defined in MyGL.obj
1>G:\Development\Test\Debug\Test.exe : fatal error LNK1169: one or more multiply defined symbols found
I've also already made sure that "#pragma once" was in ever file, header guards, adding "OpenGL32.lib" into the additional dependencies in visual studio, adding a pragma comment for the lib, setting the pointers equal to null in the declaration, and I'm just at a complete loss for anything else to try, even after googling the issue. And in my case, using GLEW or any other extension loading library because that is exactly what I'm trying to create.
In C and C++ there's an important difference between declaration and definition. A statement of the form
extern <type> <symbol>;
declares that there is some symbol somewhere, but it doesn't actually bring it into existence. It's more like a promise to the compiler, that the symbol will be defined somewhere else. When you wrote
extern PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB;
extern PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB;
you actually didn't create the variables for those function pointers, you just "listed them in the table of contents" for your program. You actually have to define them somewhere. I.e. in some compilation unit you have to write (without the extern).
PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB;
PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB;
This has absolutely nothing to do with initialization, as hinted by #EricLopushansky; it's all about them being getting actually defined. Since these are global scope, they'll be initialized to 0 anyway, even if you don't explicitly write that = 0.
This isn't very well explained by the OpenGL wiki in the article Load OpenGL Functions but simply do the following. Setting the pointer to null within the cpp file will fix the issue.
For example:
PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = NULL;
For anyone interested, here is the relevant code from GLEW that serves the same purpose:
//glew.h
#ifdef GLEW_STATIC
# define GLEWAPI extern
#else
# ifdef GLEW_BUILD
# define GLEWAPI extern __declspec(dllexport)
# else
# define GLEWAPI extern __declspec(dllimport)
# endif
#endif
#define GLEW_FUN_EXPORT GLEWAPI
//wglew.h
#define WGLEW_GET_FUN(x) x
#define wglChoosePixelFormatARB WGLEW_GET_FUN(__wglewChoosePixelFormatARB)
typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
#define WGLEW_FUN_EXPORT GLEW_FUN_EXPORT
WGLEW_FUN_EXPORT PFNWGLCHOOSEPIXELFORMATARBPROC __wglewChoosePixelFormatARB;
//glew.c
# define glewGetProcAddress(name) wglGetProcAddress((LPCSTR)name)
PFNWGLCHOOSEPIXELFORMATARBPROC __wglewChoosePixelFormatARB = NULL;
r = ((wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)glewGetProcAddress((const GLubyte*)"wglChoosePixelFormatARB")) == NULL) || r;
//I would be using this static so it would evaluate in my code to
//MyGLOpenGL.h
#define wglChoosePixelFormatARB __wglewChoosePixelFormatARB
typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
extern PFNWGLCHOOSEPIXELFORMATARBPROC __wglewChoosePixelFormatARB;
//MyGLOpenGL.cpp
PFNWGLCHOOSEPIXELFORMATARBPROC __wglewChoosePixelFormatARB = NULL;
wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress((const GLubyte*)"wglChoosePixelFormatARB")
I am trying to use NtOpenProcess() I have not find any example in town.
I am getting an error any help is much appreciated.
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE prevInstance, PSTR szCmdLine, int showCmd)
{
HANDLE handle;
HWND myWindow =FindWindow(NULL, L"Notepad");
PCLIENT_ID PID;
GetWindowThreadProcessId(myWindow, (LPDWORD)&PID);
ZwOpenProcess(&handle, PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, NULL,PID);
return 0;
}
The errors are
1>c:\users\asus\source\repos\windowsproject2\windowsproject2\windowsproject2.cpp(14): error C2065: 'PCLIENT_ID': undeclared identifier
1>c:\users\asus\source\repos\windowsproject2\windowsproject2\windowsproject2.cpp(14): error C2146: syntax error: missing ')' before identifier 'PID'
1>c:\users\asus\source\repos\windowsproject2\windowsproject2\windowsproject2.cpp(14): error C3861: 'NtOpenProcess': identifier not found
1>c:\users\asus\source\repos\windowsproject2\windowsproject2\windowsproject2.cpp(14): error C2146: syntax error: missing ';' before identifier 'PID'
1>c:\users\asus\source\repos\windowsproject2\windowsproject2\windowsproject2.cpp(14): error C2059: syntax error: ')'
This are my include files.
#include <Windows.h>
#include <ntddk.h>
#include <Ntifs.h>
#include "stdafx.h"
at first look at code:
FindWindow(NULL, L"Notepad");
faster of all you want
FindWindow(L"Notepad", 0);
because L"Notepad" is class name (not window name) and class name first parameter.
PCLIENT_ID PID;
GetWindowThreadProcessId(myWindow, (LPDWORD)&PID);
the GetWindowThreadProcessId wait pointer to DWORD memory, where it store process id. but you pass to it uninitialized pointer, to random memory. need use this:
CLIENT_ID pid = { };
if (GetWindowThreadProcessId(myWindow, (PDWORD)&pid.UniqueProcess))
finally ObjectAttributes in call NtOpenProcess is mandatory parameter and can not be 0.
about undeclared identifiers - all this declared in ntifs.h and it sub-headers (ntifs.h include ntddk.k - so you not need include it direct). problem that windows.h and ntifs.h is conflict - many common declarations. if you include both - you got a lot of errors. but solution exist - include ntifs.h in some namespace. but even after this you got some errors. but this also can be fixed, if deep understand source of errors. also you will be need include own code to this namespace too, for have easy access to ntifs declarations. and finally you need use ntdll.lib or ntdllp.lib (will be conflict with CRT libs if you use it) as linker input.
so if you want use native api in own code, without add custom headers, where you copy-paste some nt definitions and call it without resolve api in runtime, but use static linking - this is possible, but require deep knowledge and understanding what you doing. example
#define DECLSPEC_DEPRECATED_DDK
#define _XX_BEGIN namespace XX {
#define _XX_END }
_XX_BEGIN
struct _SECURITY_QUALITY_OF_SERVICE;
struct _CONTEXT;
_XX_END
#define _INC_MMSYSTEM /* Prevent inclusion of mmsystem.h in windows.h */
#include <windows.h>
#pragma warning(disable : 4005)
_XX_BEGIN
#ifdef _RTL_RUN_ONCE_DEF
#undef _RTL_RUN_ONCE_DEF
#endif
#define RtlCompareMemory ::RtlCompareMemory
#include <ntifs.h>
_XX_END
#undef _INC_MMSYSTEM /* Prevent inclusion of mmsystem.h in windows.h */
#include <MMSystem.h>
_XX_BEGIN
void demo()
{
if (HWND myWindow = FindWindow(L"Notepad", 0))
{
CLIENT_ID pid = { };
if (GetWindowThreadProcessId(myWindow, (PDWORD)&pid.UniqueProcess))
{
HANDLE handle;
static OBJECT_ATTRIBUTES zoa = { sizeof(zoa) };
if (0 <= NtOpenProcess(&handle,
PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE,
&zoa, &pid))
{
NtClose(handle);
}
}
}
}
_XX_END
Here is the minimal C program to reproduce:
#include <alsa/asoundlib.h>
#include <sys/time.h>
int main( void )
{
}
This will compile with gcc -c -o timealsa.o timealsa.c, but if you include the -std=c99 switch, you get a redefinition error:
In file included from /usr/include/sys/time.h:28:0,
from timealsa.c:3:
/usr/include/bits/time.h:30:8: error: redefinition of ‘struct timeval’
struct timeval
^
In file included from /usr/include/alsa/asoundlib.h:49:0,
from timealsa.c:2:
/usr/include/alsa/global.h:138:8: note: originally defined here
struct timeval {
^
How can I resolve this conflict while still using -std=c99?
Since your question suggests you are using GLIBC's time.h there is a way to avoid this by telling it not to define timeval. Include asoundlib.h first then define _STRUCT_TIMEVAL. The one defined in asoundlib.h will be the one that gets used.
#include <alsa/asoundlib.h>
#ifndef _STRUCT_TIMEVAL
# define _STRUCT_TIMEVAL
#endif
#include <sys/time.h>
int main( void )
{
}
With C99 and later you can't have duplicate definitions of the same struct. The problem is that alsa/asoundlib.h includes alsa/global.h which contains this code:
/* for timeval and timespec */
#include <time.h>
...
#ifdef __GLIBC__
#if !defined(_POSIX_C_SOURCE) && !defined(_POSIX_SOURCE)
struct timeval {
time_t tv_sec; /* seconds */
long tv_usec; /* microseconds */
};
struct timespec {
time_t tv_sec; /* seconds */
long tv_nsec; /* nanoseconds */
};
#endif
#endif
So the Michael Petch's solution won't work - by the time you've included alsa/asoundlib.h it is already too late. The proper solution is to define _POSIX_C_SOURCE (_POSIX_SOURCE is obsolete). There's more information about these macros here and here.
For example you could try -D_POSIX_C_SOURCE=200809L. However, if you do that you'll get errors like this:
/usr/include/arm-linux-gnueabihf/sys/time.h:110:20: error: field ‘it_interval’ has incomplete type
struct timeval it_interval;
^
/usr/include/arm-linux-gnueabihf/sys/time.h:112:20: error: field ‘it_value’ has incomplete type
struct timeval it_value;
^
/usr/include/arm-linux-gnueabihf/sys/time.h:138:61: error: array type has incomplete element type
extern int utimes (const char *__file, const struct timeval __tvp[2])
^
This is all a big mess of old C code and macro madness. The only way I got it to work was to give up and use -std=gnu11.
I am working on a project where I have to support IPv6 addressing scheme. This requires me to replace winsock.h with winsock2.h to make IP-version independent calls. Initially, I faced redefinition related errors which I could remove by employing solutions available online (placing #include <winsock2.h> before #include <windows.h>; including #define_WINSOCKAPI_). However, I am still getting errors like:
2>../include\obsocket.h(171) : error C2143: syntax error : missing '}' before 'constant'
2>../include\obsocket.h(171) : error C2059: syntax error : 'constant'
2>../include\obsocket.h(171) : error C2143: syntax error : missing ';' before '}'
2>../include\obsocket.h(171) : error C2238: unexpected token(s) preceding ';'
2>../include\obsocket.h(173) : error C2065: 'ShutdownType' : undeclared identifier
2>../include\obsocket.h(177) : error C2146: syntax error : missing ';' before identifier 'GetDescriptor'
2>../include\obsocket.h(177) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
2>../include\obsocket.h(177) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
2>../include\obsocket.h(177) : error C2065: '_sock' : undeclared identifier
2>../include\obsocket.h(179) : error C2065: '_timeout' : undeclared identifier
2>../include\obsocket.h(180) : error C2065: '_use_blocking_calls' : undeclared identifier
2>../include\obsocket.h(181) : error C2065: '_req_pending' : undeclared identifier
2>../include\obsocket.h(185) : error C2270: 'ToString' : modifiers not allowed on nonmember functions
2>../include\obsocket.h(187) : error C2059: syntax error : 'private'
2>../include\obsocket.h(189) : error C2146: syntax error : missing ';' before identifier '_sock'
2>../include\obsocket.h(189) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
2>../include\obsocket.h(189) : error C2086: 'int SOCK_TYPE' : redefinition
2>../include\obsocket.h(177) : see declaration of 'SOCK_TYPE'
2>../include\obsocket.h(189) : error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
2>../include\obsocket.h(189) : error C2371: '_sock' : redefinition; different basic types
2>../include\obsocket.h(199) : error C2371: '_use_blocking_calls' : redefinition; different basic types
2>../include\obsocket.h(200) : error C2371: '_timeout' : redefinition; different basic types
2>../include\obsocket.h(201) : error C2371: '_req_pending' : redefinition; different basic types
2>../include\obsocket.h(203) : error C2146: syntax error : missing ')' before identifier 'sock'
2>../include\obsocket.h(203) : error C2146: syntax error : missing ';' before identifier 'sock'
2>../include\obsocket.h(203) : error C2371: 'SOCK_TYPE' : redefinition; different basic types
I've made sure that winsock.h is not getting included anywhere during the build (by enabling show includes during the build).
Here is the code for obsocket.h:
#ifndef _obsocket_h
#define _obsocket_h
#ifdef _WIN32
#include <winsock2.h>
#include <ws2tcpip.h>
//#include <winsock.h>
#else
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#endif
class ObSocket {
public:
#ifdef _WIN32
typedef SOCKET SOCK_TYPE;
#else
typedef int SOCK_TYPE;
#endif
ObSocket();
~ObSocket();
enum ShutdownType { SD_INCOMING = 0, SD_OUTGOING = 1, SD_BOTH = 2 };
ObStatus Shutdown(ShutdownType);
ObStatus Close();
bool IsValid();
SOCK_TYPE GetDescriptor() { return _sock; }
void NonBlocking(int timeout);
inline int GetTimeout( ) { return _timeout; }
inline bool IsBlocking( ) { return _use_blocking_calls; }
inline int IncPendingReq(int i = 1) { _req_pending += i; return _req_pending; }
inline int DecPendingReq(int i = 1) { _req_pending -= i; return _req_pending; }
inline int GetPendingReq( ) { return _req_pending; }
ObString& ToString(ObString& strClass) const;
private:
SOCK_TYPE _sock;
ObInetAddress _addr;
char _my_addr[20];
in_port_t _my_port;
char _remote_addr[20];
in_port_t _remote_port;
bool _use_blocking_calls;
int _timeout;
int _req_pending;
ObSocket(SOCK_TYPE sock);
void SetAddr(sockaddr_in& inAddr, const ObInetAddress& addr, in_port_t port);
void ReallocFileDescriptor();
ObSocket(const ObSocket&);
ObSocket& operator=(const ObSocket&);
static void Initialize();
static void Finalize();
};
Can anyone help in pointing out what could be going wrong?
I don't want to compile dynamic libs, so this question was not useful.
I downloaded taglib and compiled it using:
cmake -DENABLE_STATIC=ON -DENABLE_STATIC_RUNTIME=ON -DWITH_MP4=ON -G "Visual Studio 10"
That generates the Visual Studio solutions and I can compile the "tag" project which produces tag.lib in taglib/Release.
The problem comes when I try to use the library in a test application - nothing much, just a simple test:
#include "stdafx.h"
#include "fileref.h"
int _tmain(int argc, _TCHAR* argv[])
{
TagLib::FileRef d("");
return 0;
}
I get the following Linker errors:
Error 1 error LNK2001: unresolved external symbol "__declspec(dllimport) public: virtual __thiscall TagLib::FileRef::~FileRef(void)" (__imp_??1FileRef#TagLib##UAE#XZ) C:\...\taglib_test\taglib_test\taglib_test.obj taglib_test
Error 2 error LNK2001: unresolved external symbol "__declspec(dllimport) public: __thiscall TagLib::FileRef::FileRef(class TagLib::FileName,bool,enum TagLib::AudioProperties::ReadStyle)" (__imp_??0FileRef#TagLib##QAE#VFileName#1#_NW4ReadStyle#AudioProperties#1##Z) C:\...\taglib_test\taglib_test\taglib_test.obj taglib_test
Error 4 error LNK2001: unresolved external symbol "__declspec(dllimport) public: __thiscall TagLib::FileName::FileName(char const *)" (__imp_??0FileName#TagLib##QAE#PBD#Z) C:\...\taglib_test\taglib_test\taglib_test.obj taglib_test
Error 3 error LNK2001: unresolved external symbol "__declspec(dllimport) public: __thiscall TagLib::FileName::~FileName(void)" (__imp_??1FileName#TagLib##QAE#XZ) C:\...\taglib_test\taglib_test\taglib_test.obj taglib_test
Error 5 error LNK1120: 4 unresolved externals C:\...\taglib_test\Release\taglib_test.exe taglib_test
Can somebody please give me an idea as to what's going on here?
The following are the preprocessor defines in the tag project:
WIN32
_WINDOWS
NDEBUG
HAVE_CONFIG_H
_CRT_SECURE_NO_DEPRECATE
_CRT_NONSTDC_NO_DEPRECATE
TAGLIB_STATIC
CMAKE_INTDIR="Release"
For those who have had this problem:
I fixed it by defining TAGLIB_STATIC in the test project:
#include "stdafx.h"
//This should have been generated by the build system in taglib_config.h
//but was not.
#define TAGLIB_STATIC
#include "fileref.h"
int _tmain(int argc, _TCHAR* argv[])
{
TagLib::FileRef d("");
return 0;
}