This question already has answers here:
Visual Studio error with 'timespec' structure
(5 answers)
Closed 6 years ago.
While executing a Pthread program in C using Visual Studio 2015, I got the following error:
Error C2011 'timespec': 'struct' type redefinition
The following is my code:
#include<pthread.h>
#include<stdlib.h>
#include<stdio.h>
void *calculator(void *parameter);
int main(/*int *argc,char *argv[]*/)
{
pthread_t thread_obj;
pthread_attr_t thread_attr;
char *First_string = "abc"/*argv[1]*/;
pthread_attr_init(&thread_attr);
pthread_create(&thread_obj,&thread_attr,calculator,First_string);
}
void *calculator(void *parameter)
{
int x=atoi((char*)parameter);
printf("x=%d", x);
}
The pthread.h header file contains the following code related to timespec:
#if !defined(HAVE_STRUCT_TIMESPEC)
#define HAVE_STRUCT_TIMESPEC
#if !defined(_TIMESPEC_DEFINED)
#define _TIMESPEC_DEFINED
struct timespec {
time_t tv_sec;
long tv_nsec;
};
#endif /* _TIMESPEC_DEFINED */
#endif /* HAVE_STRUCT_TIMESPEC */
No other header file which I use uses the timespec struct, so there is no chance of redefining. There is no chance of a corrupted header file because it has been downloaded from pthread opensource website.
pthreads-win32 (which I assume you're using) may internally include time.h (time.h is also commonly included by other libraries/headers) - and time.h already declares timespec (also, it does so in a way compatible with pthreads) - yet the pthreads-win32's pthread.h doesn't have the valid include guards for this case (shame on them!). pthreads tries to declare it because it needs it internally, but since it's possible it won't need the entire time.h, it tries to declare only the timespec if possible. Still, you can simply add
#define HAVE_STRUCT_TIMESPEC
before #include <pthread.h> - that will tell the pthreads-win32 header that you already have a proper timespec, and will let your code compile properly.
Alternatively, if you're using pthreads extensively, you may wish to edit the header file itself - simply add that #define HAVE_STRUCT_TIMESPEC to it somewhere near the beginning, and you're good to go.
Further reading: http://mingw-users.1079350.n2.nabble.com/mingw-error-redefinition-of-struct-timespec-td7583722.html
Related
I've been developing in C using eclipse as my IDE in my virtual machine with ubuntu, I've made some progress and I wanted to test them in the real product which is an embedded system using powerpc.
In order to compile that program for our product I use Code::Blocks in Windows but the compiler is a powerpc version of the gcc.
The same code is giving me an error in the powerpc version that doesn't appear in the ubuntu version.
I have two header files gral.h and module_hand.h as follows:
The gral.h file:
#ifndef HEADERS_GRAL_H_
#define HEADERS_GRAL_H_
#include "module_hand.h"
typedef struct PROFILE
{
module_t mod; // this one comes from module_hand.h
int var1; // some other random variables
} profile_t;
#endif /* HEADERS_GRAL_H_ */
The module_hand.h is defined as follows
#ifndef HEADERS_MODULE_HAND_H_
#define HEADERS_MODULE_HAND_H_
#include <stdint.h>
#include "gral.h"
typedef struct PROFILE profile_t;
typedef struct module
{
char name[30]; // name of module
char rev[30]; // module revision
char mfr[30]; // manufacturer
} module_t;
int Mod_Init(profile_t *profile);
/* some other random functions */
#endif /* HEADERS_MODULE_HAND_H_*/
As you'll see, I don't use the PROFILE struct in the module struct, But I declare it forward to use it in the declaration of the Mod_Init function
This gives me a Error: redefinition of typedef 'profile_t'
and error: previous declaration of 'profile_t' was here
If I remove the forward declaration the error is Error: parse error before '*' token
where the line number is the line of the function declaration.
My doubt is what am I missing, and why gcc in Ubuntu does compile it with no problem.
Your powerpc compiler is enforcing the C99 rule that
If an identifier has no linkage, there shall be no more than one
declaration of the identifier (in a declarator or type specifier) with
the same scope and in the same name space, except for tags as
specified in 6.7.2.3.
(C99 6.7/3)
Your Linux compiler is observing the relaxed version of that rule that was introduced in C11:
If an identifier has no linkage, there shall be no more than one
declaration of the identifier (in a declarator or type specifier) with
the same scope and in the same name space, except that:
a typedef name may be redefined to denote the same type as it currently does, provided that type is not a variably modified type;
tags may be redeclared as specified in 6.7.2.3.
(C11 6.7/3; also C17 6.7/3)
Supposing that the compilation options are the same, the behavior difference surely arises from using different versions of GCC. More recent versions default to more recent versions of the language.
You could try adding -std=gnu11 or -std=c11 to the command-line options (for both targets) to try to get consistency. If your powerpc version of GCC is too old to accept those then you really need to update to a newer version.
Note also, however, that you don't need to have this problem in the first place. Given that module_hand.h includes gral.h, the former has no need whatever to redefine a typedef that the latter already defines.
Moreover, the fact that these two headers each include the other is a strong suggestion that they ought to be combined into one. Multiple-inclusion guards prevent an actual loop, but they are not an adequate solution.
In the gral.h header file, you define profile_t using typedef, then you redefine profile_t with another typedef in module_hand.h. You should just define the struct PROFILE in gral_h and include gral.h in module_hand.h.
gral.h:
#ifndef HEADERS_GRAL_H_
#define HEADERS_GRAL_H_
#include "module_hand.h"
typedef struct PROFILE {
module_t mod; // this one comes from module_hand.h
int var1; // some other random variables
} profile_t;
#endif /* HEADERS_GRAL_H_ */:
module_hand.h:
#ifndef HEADERS_MODULE_HAND_H_
#define HEADERS_MODULE_HAND_H_
#include <stdint.h>
typedef struct module
{
char name[30]; // name of module
char rev[30]; // module revision
char mfr[30]; // manufacturer
} module_t;
int Mod_Init(struct PROFILE *profile);
/* some other random functions */
#endif /* HEADERS_MODULE_HAND_H_*/
Well I read your answers and comments and decided to try another approach.
As some of you said, I had some kind of recursion, I wanted to keep every structure within its respective header file, but now, I dropped the idea and merged the structures in one file only.
My new approach:
Gral.h
#ifndef HEADERS_GRAL_H_
#define HEADERS_GRAL_H_
typedef struct module
{
char name[30]; // name of module
char rev[30]; // module revision
char mfr[30]; // manufacturer
} module_t;
typedef struct PROFILE {
module_t mod; // this one comes from module_hand.h
int var1; // some other variables
} profile_t;
#endif /* HEADERS_GRAL_H_ */:
Module.h
#ifndef HEADERS_MODULE_HAND_H_
#define HEADERS_MODULE_HAND_H_
#include <Gral.h>
int Mod_Init(profile_t *profile);
/* some other functions */
#endif /* HEADERS_MODULE_HAND_H_*/
And when any other structure comes up, I'll declare it in Gral.h and include the header file.
Regarding the compilers, they aren't the same version. The powerpc is quite old now. That would explain the powerpc compilation errors.
Thank you again.
Information:
LabVIEW: 2019
Version: 19.0.1 (32-bit)
Operating system: Windows 64-bit
Labview crashes completely after an indefinite time. I call three functions of the C-DLL. I loop through all the functions of the DLL over and over again. After about 2 minutes to an hour Labview crashes without reason.
Calling of OpenConnection():
Calling of QueryOpenConnectionStatus():
Calling of CloseConnection():
Type definition of TConnectionResult
Follow the given Headerfile.h
#ifndef __epMCOMLib_h_
#define __epMCOMLib_h_
#include <stdint.h>
#include <stddef.h>
#define DLLIMPORT __declspec(dllimport)
#pragma pack (push,1)
typedef struct {
uint16_t DLLFailureCode;
uint8_t ConnectionStatus;
uint32_t SystemFailureCode;
} TConnectionResult;
#pragma pack (pop)
#ifdef __cplusplus
extern "C" {
#endif
DLLIMPORT uint16_t __cdecl OpenConnection(uint8_t PortType,
char * PortName,
uint32_t OnConnectSucces,
uint32_t * Handle);
DLLIMPORT void __cdecl QueryOpenConnectionStatus(uint32_t Handle,
TConnectionResult * Result);
DLLIMPORT uint16_t __cdecl CloseConnection(uint32_t Handle);
#ifdef __cplusplus
} // extern "C"
#endif
#endif //#ifndef __epMCOMLib_h_
The DLL works perfectly. For this I integrated the DLL in Python ,LabWindows/CVI, C++ and Delphi. There is no crash in these programming languages!
Can anyone give me any useful tips on how to further isolate or eliminate the error.
Even if a function of the DLL has been executed and the DLL is then closed, it still causes a crash. As if it's still in memory. It feels like looking for a needle in a haystack.
Run the thread on the UI thread instead of any thread!
In the log file of the DLL I could see that the thread is attached and detached. I suspect this is causing a memory violation. Since Labview is shot down by its called DLL.
In my experience, sometimes DLL called with LabVIEW causes this kind of problems and with no specific reasons and solutions (even for the NI technical support).
Try to launch your LabVIEW applicatin with Administrator privilegies. In some cases, this solves the problem.
How to create a DLL library in C++ and then use it in C project VisualStudio(2015) ?
I've seen only 1 question similar to my problem ,but I couldn't understand too much from it.
I've seen lots of tutorials on how to use .dll written in C++ into another C++ project, a C .dll used in C#, but no example of how to use a C++ .dll into a C VS project.
I really need help, I've searched all over the internet, tried all kind of 'solutions' to my problem, still, without any solution.
I really need your help on this one.
The C++ dll Project has the following content :
//C++ dll Header Library, having the name "dllDelay.h":
#include <iostream>
#include <stdio.h>
#include <windows.h>
extern "C" __declspec(dllexport) void dllDelay(DWORD dwMsec);
#endif
//C++ .cpp file named "dllDelay.cpp":
#include "dllDelay.h"
#include "stdafx.h"
extern "C" __declspec(dllexport)
void dllDelay(DWORD dwMsec) {
Sleep(dwMsec);
}
The C VisualStudio(2015) Project has the following content :
/*This function is intended to Delay 10 seconds, measure that elapsed time
and write it into a file. I've checked this function using Sleep() instead of
dllDelay() and it worked fine, so this function has no errors.*/
#include "dllDelay.h"
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <windows.h>
int main(void)
{
FILE *write1;
// measure elapsed time on windows with QueryPerformanceCounter() :
LARGE_INTEGER frequency; // ticks per second
LARGE_INTEGER t1, t2; // ticks
double elapsedTime;
write1 = fopen("write_difftime_1Test.txt", "w");
fprintf(write1, "\n Sleep : 10000ms = 10s");
time_t start, stop;
clock_t ticks;
long count;
double i = 0, v = 0, j = 0;
//make 10 such measurements and write them into file
while ((j < 10) && ((write1 != NULL) && (TRUE != fseek(write1, 0L, SEEK_END))))
{
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&t1);
time(&start);
//The function from dll
dllDelay(10000);
time(&stop);
QueryPerformanceCounter(&t2);
// compute and print the elapsed time in millisec
elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
fprintf(write1, "\n Elapsed time : %lf s. timeDiff time: %f in seconds\n\n", elapsedTime / 1000, difftime(stop, start));
j++;
}
fclose(write1);
return 0;
}
`
This function is intended to Delay 10 seconds, measure that elapsed time
and write it into a file. I've checked this function using Sleep() instead of
dllDelay() and it worked fine, so this function has no errors.
But when I use #include "dllDelay.h" I get 3111 Errors such as :
expected a '{'
identifier *write1 is undefined from FILE *write1;
identifier clock_t is undefined from clock_t ticks;
declaration is incompatible with "float log10(float_Xx)" (declared at line 227) - in cmath - a standard file where we have using _CSTD log10; using _CSTD modf; using _CSTD pow;
declaration is incompatible with "double pow(double_Xx, int _Yx)" (declared at line 22) - in cmath - a standard file where we have using _CSTD log10; using _CSTD modf; using _CSTD pow;
so in the file cmath - the whole file is signaled as being with errors
and many other errors of such type - meaning that the 2 languages are mangled somehow.
I built the dll (in a dll project, of course), copied the .dll file into the C Project folder where the exe is found, I added to the solution Explorer the .lib file and got these errors.
I really neeed your help, I've looked everywhere and did not found a guide or anything regarding the usage of a C++ .dll used in a C project. :|
Thank you for your time.
In your C++ DLL project open the project properties and define a preprocessor symbol:
Then in your header file, define another symbol based on whether the preprocessor symbol circled in red is defined or not:
#ifdef CPPDLL_EXPORTS
#define DLLIMPORT_EXPORT __declspec(dllexport)
#else
#define DLLIMPORT_EXPORT __declspec(dllimport)
#endif
Then use that defined symbol in front of your function declaration:
DLLIMPORT_EXPORT void dllDelay(DWORD dwMsec);
This has the following effect:
In your DLL project, the symbol (DLLIMPORT_EXPORT) is defined. Thus, DLLIMPORT_EXPORT will evaluate to __declspec(dllexport). In your C project, which consumes the DLL, the symbol will not be defined. Ergo, DLLIMPORT_EXPORT evaluates to __declspec(dllimport) when the header file is included. Doing this will import the function and you will be able to use it. Failure to do so will result in a Linker error (unresolved external symbol) when trying to call the function.
Hope this helps!
PS: You should move all #includes that aren't needed in your header file to your implementation (CPP) file :-)
I have written a multithread server program in C, which echoes back all the data that a client sends.
Initially, I used poll() function in my program to detect POLLRDHUP event, for that I defined _GNU_SOURCE macro (This event is defined here).
Later I updated my code & removed poll() function, however I forgot to remove _GNU_SOURCE macro.
Now my code is finally complete (and a little long to post, more than 250 lines). Before removing macro I was compiling my program using:
gcc multi_thread_socket_v4.c -Wall -Werror -g -lpthread -o multi_thread_socket
and it worked fine: No errors, no warnings
After I removed the macro definition, and compiled using same command-line, the output of gcc was:
multi_thread_socket_v4.c: In function ‘main’:
multi_thread_socket_v4.c:194: warning: implicit declaration of function ‘pthread_mutexattr_settype’
multi_thread_socket_v4.c:194: error: ‘PTHREAD_MUTEX_ERRORCHECK’ undeclared (first use in this function)
multi_thread_socket_v4.c:194: error: (Each undeclared identifier is reported only once
multi_thread_socket_v4.c:194: error: for each function it appears in.)
I have included all the required libraries as it worked fine initially.
I peeked into pthread.h at /usr/include/pthread.h and found out this:
/* Mutex types. */
enum
{
PTHREAD_MUTEX_TIMED_NP,
PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_ADAPTIVE_NP
#ifdef __USE_UNIX98
,
PTHREAD_MUTEX_NORMAL = PTHREAD_MUTEX_TIMED_NP,
PTHREAD_MUTEX_RECURSIVE = PTHREAD_MUTEX_RECURSIVE_NP,
PTHREAD_MUTEX_ERRORCHECK = PTHREAD_MUTEX_ERRORCHECK_NP,
PTHREAD_MUTEX_DEFAULT = PTHREAD_MUTEX_NORMAL
#endif
#ifdef __USE_GNU
/* For compatibility. */
, PTHREAD_MUTEX_FAST_NP = PTHREAD_MUTEX_TIMED_NP
#endif
};
and this:
#ifdef __USE_UNIX98
/* Return in *KIND the mutex kind attribute in *ATTR. */
extern int pthread_mutexattr_gettype (__const pthread_mutexattr_t *__restrict
__attr, int *__restrict __kind)
__THROW __nonnull ((1, 2));
/* Set the mutex kind attribute in *ATTR to KIND (either PTHREAD_MUTEX_NORMAL,
PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK, or
PTHREAD_MUTEX_DEFAULT). */
extern int pthread_mutexattr_settype (pthread_mutexattr_t *__attr, int __kind)
__THROW __nonnull ((1));
I checked out here to check if __USE_UNIX98 is a feature test macro, but it was not there.
So please help me understanding the reasons for the error, because the function & the macro where gcc shows error are defined in POSIX standard. I do not know what more info regarding my problem will be required so please tell me, I will update my question.
You should use
#define _POSIX_C_SOURCE 200112L
if you want to use POSIX features such as pthread_mutexattr_settype ... see http://pubs.opengroup.org/onlinepubs/007904975/functions/xsh_chap02_02.html
Another possibility is
#define _XOPEN_SOURCE 700
See http://man7.org/linux/man-pages/man7/feature_test_macros.7.html and http://pubs.opengroup.org/onlinepubs/9699919799/
Setting _GNU_SOURCE includes POSIX and lots of other definitions.
P.S. I would expect that including <pthread.h> includes <features.h>, which by default defines _POSIX_C_SOURCE as 200112L, but it's possible that you have defined something that overrides that ... see /usr/include/features.h on your system for details of the symbols and their usage.
It doesn't, your problem likely lies elsewhere.
I just compiled a trivial program with the following content:
#include <pthread.h>
int main(int argc, char **argv)
{
pthread_mutexattr_t attr;
pthread_mutexattr_init(&attr);
pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK);
return 0;
}
This compiles perfectly with gcc -pthread -Wall -Werror a.c.
It's possible that another part of your program causes this, by eg. doing something silly like defining _PTHREAD_H, or some other minor sabotage.
You might want to try to get a minimal test case by using a tool like delta or creduce, which will probably make the problem evident.
When you're using old libraries (e.g. 2.1.x) you should use
#define __USE_UNIX98
Using a macro beginning with "__" it's not usually a good idea, but sometimes it's the only way... see also this discussion
I'm just getting started with modular programming in C. I think I'm doing something wrong with the inclusions, because I'm getting a lot of conflicting types for 'functionName' and previous declaration of 'functionName' was here errors. I did put inclusion guards in place.
Do you know a clear tutorial that explains modular programming in C, especially how the inclusions work?
Update: I have tried to isolate my issue. Here's some code, as requested.
Update 2: updated code is below. The errors have been updated, too.
/*
* main.c
*/
#include <stdio.h>
#include "aStruct.h"
int main() {
aStruct asTest = createStruct();
return 0;
}
/*
* aStruct.h
*/
#ifndef ASTRUCT_H_
#define ASTRUCT_H_
struct aStruct {
int value1;
int value2;
struct smallerStruct ssTest;
};
typedef struct aStruct aStruct;
aStruct createStruct();
#endif /* ASTRUCT_H_ */
/*
* smallerStruct.h
*/
#ifndef SMALLERSTRUCT_H_
#define SMALLERSTRUCT_H_
struct smallerStruct {
int value3;
};
typedef struct smallerStruct smallerStruct;
smallerStruct createSmallerStruct();
#endif /* SMALLERSTRUCT_H_ */
/*
* aStruct.c
*/
#include <stdio.h>
#include "smallerStruct.h"
#include "aStruct.h"
aStruct createStruct() {
aStruct asOutput;
printf("This makes sure that this code depends on stdio.h, just to make sure I know where the inclusion directive should go (main.c or aStruct.c).\n");
asOutput.value1 = 5;
asOutput.value2 = 5;
asOutput.ssTest = createSmallerStruct();
return asOutput;
}
/*
* smallerStruct.c
*/
#include <stdio.h>
#include "smallerStruct.h"
smallerStruct createSmallerStruct() {
smallerStruct ssOutput;
ssOutput.value3 = 41;
return ssOutput;
}
This generates the following error messages:
At aStruct.h:10
field 'ssTest' has incomplete type
At main.c:8
unused variable `asTest' (this one makes sense)
The base of inclusion is to make sure that your headers are included only once. This is usually performed with a sequence like this one:
/* header.h */
#ifndef header_h_
#define header_h_
/* Your code here ... */
#endif /* header_h_ */
The second point is to take care of possible name conflicts by handling manually pseudo namespaces with prefixes.
Then put in your headers only function declarations of public API. This may imply to add typedefs and enums. Avoid as much as possible to include constant and variable declarations: prefer accessor functions.
Another rule is to never include .c files, only .h. This is the very point of modularity: a given module dependant of another module needs only to know its interface, not its implementation.
A for your specific problem, aStruct.h uses struct smallerStruct but knows nothing about it, in particular its size for being able to allocate an aStruct variable. aStruct.h needs to include smallerStruct.h. Including smallerStruct.h before aStruct.h in main.c doesn't solve the issue when compiling aStruct.c.
The multiple definition problem is most likely coming from the way you're including the code. You are using #include "aStruct.c" as opposed to #include "aStruct.h". I suspect you are also compiling the .c files into your project in addition to the #include. This causes the compiler to become confused due to the multiple definitions of the same function.
If you change the #include to #include "aStruct.h" and make sure the three source files are compiled and linked together, the error should go away.
Such errors mean that function declaration (return type or parameter count/types) differs from other function declarations or function definition.
previous declaration message points you to the conflicting declaration.