Ошибка c2011 timespec переопределение типа struct

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);
}

Rachid K.'s user avatar

Rachid K.

4,4003 gold badges10 silver badges30 bronze badges

asked Oct 14, 2015 at 0:00

Vijay Manohar's user avatar

1

Despite this question is already answered correctly, there is also another way to solve this problem.

First, problem occurs because pthreads-win32 internally includes time.h which already declares timespec struct.

To avoid this error the only thing we should do is this:

#define HAVE_STRUCT_TIMESPEC
#include <pthread.h>

answered Apr 7, 2018 at 8:15

NutCracker's user avatar

NutCrackerNutCracker

11.3k3 gold badges43 silver badges68 bronze badges

Add this compiler flag:

-DHAVE_STRUCT_TIMESPEC

answered Nov 16, 2015 at 10:56

user_0's user avatar

user_0user_0

3,17320 silver badges33 bronze badges

1

The same problem happens when compiling programs in Visual Studio 2015 that include MariaDB 10 header files (saw it with 10.1.14).

The solution there is to define the following:

STRUCT_TIMESPEC_HAS_TV_SEC
STRUCT_TIMESPEC_HAS_TV_NSEC

answered Jun 3, 2016 at 8:36

Joao Costa's user avatar

Joao CostaJoao Costa

2,5331 gold badge21 silver badges15 bronze badges

On Visual Studio 2015.

I solve the problem adding:

#define _TIMESPEC_DEFINED

answered Nov 8, 2019 at 4:01

Román Castillo's user avatar

Delete all instances of ‘TIMESPEC’ in pthread.h (Make a backup first.)

If I understand it correctly, you probably downloaded pthreads and tried installing it into your VS.

But the pthreads.h file doesn’t play nicely with the TIMESPEC defintions already defined in some other header file.

So, delete the portions of the pthreads.h file where TIMESPEC is defined.

answered Nov 7, 2015 at 21:40

jinisnotmyname's user avatar

2

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);
}

Rachid K.'s user avatar

Rachid K.

4,4003 gold badges10 silver badges30 bronze badges

asked Oct 14, 2015 at 0:00

Vijay Manohar's user avatar

1

Despite this question is already answered correctly, there is also another way to solve this problem.

First, problem occurs because pthreads-win32 internally includes time.h which already declares timespec struct.

To avoid this error the only thing we should do is this:

#define HAVE_STRUCT_TIMESPEC
#include <pthread.h>

answered Apr 7, 2018 at 8:15

NutCracker's user avatar

NutCrackerNutCracker

11.3k3 gold badges43 silver badges68 bronze badges

Add this compiler flag:

-DHAVE_STRUCT_TIMESPEC

answered Nov 16, 2015 at 10:56

user_0's user avatar

user_0user_0

3,17320 silver badges33 bronze badges

1

The same problem happens when compiling programs in Visual Studio 2015 that include MariaDB 10 header files (saw it with 10.1.14).

The solution there is to define the following:

STRUCT_TIMESPEC_HAS_TV_SEC
STRUCT_TIMESPEC_HAS_TV_NSEC

answered Jun 3, 2016 at 8:36

Joao Costa's user avatar

Joao CostaJoao Costa

2,5331 gold badge21 silver badges15 bronze badges

On Visual Studio 2015.

I solve the problem adding:

#define _TIMESPEC_DEFINED

answered Nov 8, 2019 at 4:01

Román Castillo's user avatar

Delete all instances of ‘TIMESPEC’ in pthread.h (Make a backup first.)

If I understand it correctly, you probably downloaded pthreads and tried installing it into your VS.

But the pthreads.h file doesn’t play nicely with the TIMESPEC defintions already defined in some other header file.

So, delete the portions of the pthreads.h file where TIMESPEC is defined.

answered Nov 7, 2015 at 21:40

jinisnotmyname's user avatar

2

RAXEAX

0 / 0 / 0

Регистрация: 29.08.2015

Сообщений: 12

1

05.09.2015, 20:22. Показов 12363. Ответов 16

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Доброго времени суток. Столкнулся с такой проблемой. Пытаюсь скомпилить пример из гайда по libcurl (http://curl.haxx.se/libcurl/c/multithread.html).

C
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
#define CURL_STATICLIB 
 
#include <stdio.h>
 
#pragma comment(lib,"pthreadVC2.lib")
#include <pthread.h>
 
#pragma comment(lib,"libcurl_a.lib")
#include <curl.h>
 
#define NUMT 3
 
const char * const urls[NUMT] = {
    "http://curl.haxx.se/",
    "ftp://cool.haxx.se/",
    "http://www.contactor.se/"
};
 
static void *pull_one_url(void *url)
{
    CURL *curl;
 
    curl = curl_easy_init();
    curl_easy_setopt(curl, CURLOPT_URL, url);
    curl_easy_perform(curl); /* ignores error */
    curl_easy_cleanup(curl);
    return NULL;
}
 
int main()
{
    pthread_t tid[NUMT];
    int i;
    int error;
 
    /* Must initialize libcurl before any threads are started */
    curl_global_init(CURL_GLOBAL_ALL);
 
    for (i = 0; i < NUMT; i++) {
        error = pthread_create(&tid[i],
            NULL, /* default attributes please */
            pull_one_url,
            (void *)urls[i]);
        if (0 != error)
            fprintf(stderr, "Couldn't run thread number %d, errno %dn", i, error);
        else
            fprintf(stderr, "Thread %d, gets %sn", i, urls[i]);
    }
 
    /* now wait for all threads to terminate */
    for (i = 0; i < NUMT; i++) {
        error = pthread_join(tid[i], NULL);
        fprintf(stderr, "Thread %d terminatedn", i);
    }
 
    return 0;
}

Выдает ошибку:

Код

переопределение типа "struct"	Test	d:program filesmicrosoft visual studio 14.0vcincludepthread.h 320

Как исправить данную ошибку? Заранее благодарю за любой ответ.



0



Programming

Эксперт

94731 / 64177 / 26122

Регистрация: 12.04.2006

Сообщений: 116,782

05.09.2015, 20:22

16

6044 / 2159 / 753

Регистрация: 10.12.2010

Сообщений: 6,005

Записей в блоге: 3

07.09.2015, 10:58

2

Судя по всему вы пользуете какой-то порт под винду. Выложите хэдер сюда, глянем.



0



0 / 0 / 0

Регистрация: 29.08.2015

Сообщений: 12

07.09.2015, 11:36

 [ТС]

3

Вот хэдер который подключаю:pthread.7z



0



6044 / 2159 / 753

Регистрация: 10.12.2010

Сообщений: 6,005

Записей в блоге: 3

07.09.2015, 12:29

4

Пропустите пожалуйста ваш исходник через препроцессор и выложите результат.



0



0 / 0 / 0

Регистрация: 29.08.2015

Сообщений: 12

07.09.2015, 14:40

 [ТС]

5

К своему стыду, я не знаю какой ключ компилятора (vs) отвечает за пропуск через препроцессор.



0



6044 / 2159 / 753

Регистрация: 10.12.2010

Сообщений: 6,005

Записей в блоге: 3

07.09.2015, 14:41

6

Ключ /P



0



0 / 0 / 0

Регистрация: 07.09.2015

Сообщений: 18

07.09.2015, 14:48

7

Недавно пытался зацепить pthread к VS, и чет непонятные проблемы были, попробуй скомпилить код под линуксом, если пройдет, значит точно ошибка в библиотеке подцепленной к VS.

Если хочешь, вечером сам смогу скомпилить и отписаться.

Откуда взял хедер? Линуксовый или порт под винду?
Если линуксовый, то не зацепишь.



0



0 / 0 / 0

Регистрация: 29.08.2015

Сообщений: 12

07.09.2015, 14:55

 [ТС]

8

После пропускания через препроцессор: main.zip



0



0 / 0 / 0

Регистрация: 29.08.2015

Сообщений: 12

07.09.2015, 15:00

 [ТС]

9

pthread.h отсюда. гайд с ссылкой на этот pthread взял отсюда



0



0 / 0 / 0

Регистрация: 07.09.2015

Сообщений: 18

07.09.2015, 15:03

10

Цитата
Сообщение от RAXEAX
Посмотреть сообщение

pthread.h отсюда. гайд с ссылкой на этот pthread взял отсюда

закомменти 320 строку в pthread.h

Это конечно в плане шарпа советуют, я шарп не учил, попробуй, может прокатит)



0



0 / 0 / 0

Регистрация: 29.08.2015

Сообщений: 12

07.09.2015, 15:14

 [ТС]

11

Закомментил в pthread.h 320 строку (точнее всю структуру timespec), выдал кучу ошибок компоновщик.



0



0 / 0 / 0

Регистрация: 07.09.2015

Сообщений: 18

07.09.2015, 15:17

12

Цитата
Сообщение от RAXEAX
Посмотреть сообщение

Закомментил в pthread.h 320 строку (точнее всю структуру timespec), выдал кучу ошибок компоновщик.

Вставь сюда содержание структуры пл3



0



RAXEAX

0 / 0 / 0

Регистрация: 29.08.2015

Сообщений: 12

07.09.2015, 15:26

 [ТС]

13

C
1
2
3
4
struct timespec {
        time_t tv_sec;
        long tv_nsec;
};



0



6044 / 2159 / 753

Регистрация: 10.12.2010

Сообщений: 6,005

Записей в блоге: 3

07.09.2015, 16:04

14

В общем суть проблемы у вас в том, что в мейне объявлены две структуры таймспек (одна из ptherad, вторая из time.h). Посмотрите гайды по работе с вашей либой. Там наверняка в примерах есть набор дефайнов которые надо взводить. А то руками ковырять не очень продуктивно будет. Можно попробовать взвести дефайн _UWIN перед инклудом данного исходника.



0



1 / 1 / 1

Регистрация: 08.09.2014

Сообщений: 90

18.08.2016, 23:39

15

Столкнулся с такой же проблемой, «Ошибка C2011 timespec: переопределение типа «struct» Hello,World_2 c:program files (x86)microsoft visual studio 14.0vcincludepthread.h 320″, в файле еще ничего нет, ошибка в самой библиотеке pthread.h, не подскажите что можно сделать, может кто нашел решение?



0



6044 / 2159 / 753

Регистрация: 10.12.2010

Сообщений: 6,005

Записей в блоге: 3

19.08.2016, 06:38

16

Цитата
Сообщение от HighPredator
Посмотреть сообщение

Можно попробовать взвести дефайн _UWIN перед инклудом данного исходника

unlimeted, вы вот это пробовали?



0



1 / 1 / 1

Регистрация: 08.09.2014

Сообщений: 90

19.08.2016, 22:53

17

Да, пробовал, выдает кучу ошибок типа «переменная «pthread_attr_init» не может быть инициализировано Hello,World_2 c:Program Files (x86)Microsoft Visual Studio 14.0VCincludepthread.h 891″ и т.д.

Добавлено через 1 час 16 минут
Я все тоже брал вот с этого сайта http://learnc.info/c/pthread_install.html, могу предположить что файлы там битые

Добавлено через 1 час 56 минут
Проблему решил следующим образом, скачал и установил Qt 5.5.1 с официального сайта с компилятором MinGW, нашел в ней файл pthread.h и еще несколько файлов связанных с ним, скинул их в папку include Visual Studio и все заработало, DLL и lib оставил с этого сайта http://learnc.info/c/pthread_install.html.



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

19.08.2016, 22:53

17

Everything was working well untill I moved some code from the main file to a new class, then I had the following error:

error C2011: ‘color1’ : ‘struct’ type redefinition

struct color1
{
    color1()
    {
        red = green = blue = 0;
    }

    color1(float _red, float _green, float _blue)
    {
        red = _red;
        green = _green;
        blue = _blue;
    }

    float red, green, blue;
};

Any idea ?

asked Apr 28, 2011 at 21:12

Homam's user avatar

HomamHomam

23.1k32 gold badges110 silver badges187 bronze badges

4

If the compiler says it’s redefined, then it probably is.

My psychic debugging skills tell me that you moved the struct from a source file to a header file, and forget the include guards in that header, which is then included multiple times in a source file.

EDIT: As a general rule I generally suggest avoiding leading underscores. In some cases (for example followed by a capital letter) they’re reserved for the implementation and it’s simplest to just never use leading _ instead of hoping you remember all the rules.

answered Apr 28, 2011 at 21:14

Mark B's user avatar

Mark BMark B

94.9k10 gold badges109 silver badges186 bronze badges

2

From snippet above I can’t deduce something is wrong.

But typically this error means that you are including same header files multiple times. Don’t you forget to add standard guards for include files?

#ifndef MY_HEADER_FILE_
#define MY_HEADER_FILE_

// here is your header file code

#endif

answered Apr 28, 2011 at 21:16

beduin's user avatar

beduinbeduin

7,8833 gold badges27 silver badges24 bronze badges

1

You can have the definition of the structure on a header file.
Have

 #pragma once

at the beginning of the header where the struct is defined, it solves the problem.

answered Nov 2, 2016 at 18:54

Jake OPJ's user avatar

Jake OPJJake OPJ

3412 silver badges9 bronze badges

I had the same problem and luckily did not take long figure out that it was just a silly mistake.

The thing was that I had a backup of my project at another drive (D:) but all the code was set on the drive C: when explicitly defined the full path. I created it on the C: path and was always using that way, but accidentally opened the project from the D and thought that it was the same thing, so at compile it was including twice because in some cases it was including the code from the C: path and at others from the D: path.

answered Oct 7, 2019 at 13:07

ChrCury78's user avatar

ChrCury78ChrCury78

4273 silver badges8 bronze badges

I had the same problem too, and it turned out that I made a mistake with my header guard. For example, instead of writing:

#ifndef COMMAND_H
#define COMMAND_H

// My code

#endif // COMMAND_H

I made a little and hard to recognize typo:

#ifndef COMNAND_H
#define COMMAND_H

// My code

#endif // COMMAND_H

That is, COMNAND_H not COMMAND_H. It should be the letter M rather than the letter N. I fixed that and everything was fine. Hope this answer help you with your case!!!

answered Jun 17, 2021 at 8:19

San Andreas's user avatar

This library is included in https://github.com/Ableton/push2-display-with-juce
i have cloned it to make it work with new JUCE and Visual Studio2019, seems Ableton have decided not to support it.
https://github.com/jpnielsen/push2-display-with-juce

When building in VS2019 community edition, i get this error:

1>C:Usersjpnsourcerepospush2-display-with-jucemoduleslibusblibusblibusb.h(900,28): warning C4099: 'libusb_device_handle': type name first seen using 'class' now seen using 'struct' (compiling source file ....Sourcepush2Push2-Usb-Communicator.cpp) 1>C:Usersjpnsourcerepospush2-display-with-juceSourcepush2Push2-UsbCommunicator.h(35): message : see declaration of 'libusb_device_handle' (compiling source file ....Sourcepush2Push2-Usb-Communicator.cpp) 1>C:Usersjpnsourcerepospush2-display-with-jucemoduleslibusblibusblibusb.h(970,57): warning C4099: 'libusb_device_handle': type name first seen using 'class' now seen using 'struct' (compiling source file ....Sourcepush2Push2-Usb-Communicator.cpp) 1>C:Usersjpnsourcerepospush2-display-with-jucemoduleslibusblibusblibusb.h(900): message : see declaration of 'libusb_device_handle' (compiling source file ....Sourcepush2Push2-Usb-Communicator.cpp) 1>C:Usersjpnsourcerepospush2-display-with-jucemoduleslibusblibusblibusb.h(1191,23): warning C4099: 'libusb_transfer': type name first seen using 'class' now seen using 'struct' (compiling source file ....Sourcepush2Push2-Usb-Communicator.cpp) 1>C:Usersjpnsourcerepospush2-display-with-juceSourcepush2Push2-UsbCommunicator.h(34): message : see declaration of 'libusb_transfer' (compiling source file ....Sourcepush2Push2-Usb-Communicator.cpp) 1>C:Usersjpnsourcerepospush2-display-with-jucemoduleslibusblibusblibusb.h(1202,74): warning C4099: 'libusb_transfer': type name first seen using 'class' now seen using 'struct' (compiling source file ....Sourcepush2Push2-Usb-Communicator.cpp) 1>C:Usersjpnsourcerepospush2-display-with-jucemoduleslibusblibusblibusb.h(1191): message : see declaration of 'libusb_transfer' (compiling source file ....Sourcepush2Push2-Usb-Communicator.cpp) 1>C:Usersjpnsourcerepospush2-display-with-jucemoduleslibusblibusblibusb.h(1210,24): warning C4099: 'libusb_transfer': type name first seen using 'class' now seen using 'struct' (compiling source file ....Sourcepush2Push2-Usb-Communicator.cpp) 1>C:Usersjpnsourcerepospush2-display-with-jucemoduleslibusblibusblibusb.h(1210): message : see declaration of 'libusb_transfer' (compiling source file ....Sourcepush2Push2-Usb-Communicator.cpp) 1>libusb_platform_wrapper.c 1>C:Usersjpnsourcerepospush2-display-with-jucemoduleslibusblibusbosthreads_windows.h(40,17): error C2011: 'timespec': 'struct' type redefinition 1>C:Program Files (x86)Windows Kits10Include10.0.18362.0ucrttime.h(39): message : see declaration of 'timespec' 1>Done building project "juce2push2.vcxproj" -- FAILED. ========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I added to moduleslibusblibusbosthreads_windows.h

line 29
#define HAVE_STRUCT_TIMESPEC

and the build finishes without errors

I found some references, but don’t know how to fix proper.

https://stackoverflow.com/questions/33557506/timespec-redefinition-error
https://groups.google.com/forum/#!topic/kaldi-developers/NHZx4b2JzPs

  • Ошибка c2002 фрилендер 2
  • Ошибка c2000 kyocera 2035
  • Ошибка c20 духовой шкаф самсунг
  • Ошибка c2 1712 на принтере самсунг
  • Ошибка c2 12828 1 ps vita как исправить