Меню

Ошибка 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,1323 gold badges10 silver badges29 bronze badges

asked Oct 14, 2015 at 0:00

Vijay Manohar's user avatar

1

Add this compiler flag:

-DHAVE_STRUCT_TIMESPEC

answered Nov 16, 2015 at 10:56

user_0's user avatar

user_0user_0

3,07620 silver badges32 bronze badges

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

11k2 gold badges41 silver badges68 bronze badges

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,4831 gold badge21 silver badges14 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);
}

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.

RAXEAX

0 / 0 / 0

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

Сообщений: 12

1

05.09.2015, 20:22. Показов 11247. Ответов 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,007

Записей в блоге: 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,007

Записей в блоге: 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,007

Записей в блоге: 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,007

Записей в блоге: 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,007

Записей в блоге: 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

23k32 gold badges108 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.2k10 gold badges107 silver badges185 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,7533 gold badges26 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 badges8 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

4073 silver badges7 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

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

23k32 gold badges108 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.2k10 gold badges107 silver badges185 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,7533 gold badges26 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 badges8 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

4073 silver badges7 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

При выполнении программы Pthread на C с помощью Visual Studio 2015 я получил следующую ошибку

Ошибка C2011 «timespec»: переопределение типа «структура»

Вот мой код:

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

5 ответов

Лучший ответ

Добавьте этот флаг компилятора:

-DHAVE_STRUCT_TIMESPEC


7

user_0
31 Окт 2016 в 13:14

Несмотря на то, что на этот вопрос уже дан правильный ответ, есть и другой способ решить эту проблему.

Во-первых, проблема возникает из-за того, что pthreads-win32 внутренне включает time.h, который уже объявляет timespec struct.

Чтобы избежать этой ошибки, мы должны сделать следующее:

#define HAVE_STRUCT_TIMESPEC
#include <pthread.h>


6

NutCracker
7 Апр 2018 в 08:15

Та же проблема возникает при компиляции программ в Visual Studio 2015, которые включают файлы заголовков MariaDB 10 (видел это с 10.1.14).

Решение состоит в следующем:

STRUCT_TIMESPEC_HAS_TV_SEC
STRUCT_TIMESPEC_HAS_TV_NSEC


1

Joao Costa
3 Июн 2016 в 08:36

В Visual Studio 2015.

Решаю проблему добавлением:

#define _TIMESPEC_DEFINED


0

Román Castillo
8 Ноя 2019 в 04:01

Удалите все экземпляры TIMESPEC в pthread.h (сначала сделайте резервную копию).

Если я правильно понимаю, вы, вероятно, скачали pthreads и пытались установить его в свой VS.

Но файл pthreads.h плохо сочетается с определениями TIMESPEC, уже определенными в каком-то другом заголовочном файле.

Итак, удалите части файла pthreads.h, в которых определен TIMESPEC.


-6

jinisnotmyname
31 Окт 2016 в 13:13

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка c7990 kyocera m2735
  • Ошибка c200d mazda 6 gh