Error conflicting types for си

I'm using the below code: char dest[5]; char src[5] = "test"; printf("String: %sn", do_something(dest, src)); char *do_something(char *dest, const char *src) { return dest; } The implement...

A C Function-Declaration Backgrounder

In C, function declarations don’t work like they do in other languages: The C compiler itself doesn’t search backward and forward in the file to find the function’s declaration from the place you call it, and it doesn’t scan the file multiple times to figure out the relationships either: The compiler only scans forward in the file exactly once, from top to bottom. Connecting function calls to function declarations is part of the linker’s job, and is only done after the file is compiled down to raw assembly instructions.

This means that as the compiler scans forward through the file, the very first time the compiler encounters the name of a function, one of two things have to be the case: It either is seeing the function declaration itself, in which case the compiler knows exactly what the function is and what types it takes as arguments and what types it returns — or it’s a call to the function, and the compiler has to guess how the function will eventually be declared.

(There’s a third option, where the name is used in a function prototype, but we’ll ignore that for now, since if you’re seeing this problem in the first place, you’re probably not using prototypes.)

History Lesson

In the earliest days of C, the fact that the compiler had to guess types wasn’t really an issue: All of the types were more-or-less the same — pretty much everything was either an int or a pointer, and they were the same size. (In fact, in B, the language that preceded C, there were no types at all; everything was just an int or pointer and its type was determined solely by how you used it!) So the compiler could safely guess the behavior of any function just based on the number of parameters that were passed: If you passed two parameters, the compiler would push two things onto the call stack, and presumably the callee would have two arguments declared, and that would all line up. If you passed only one parameter but the function expected two, it would still sort-of work, and the second argument would just be ignored/garbage. If you passed three parameters and the function expected two, it would also still sort-of work, and the third parameter would be ignored and stomped on by the function’s local variables. (Some old C code still expects these mismatched-argument rules will work, too.)

But having the compiler let you pass anything to anything isn’t really a good way to design a programming language. It worked well in the early days because the early C programmers were mostly wizards, and they knew not to pass the wrong type to functions, and even if they did get the types wrong, there were always tools like lint that could do deeper double-checking of your C code and warn you about such things.

Fast-forward to today, and we’re not quite in the same boat. C has grown up, and a lot of people are programming in it who aren’t wizards, and to accommodate them (and to accommodate everyone else who regularly used lint anyway), the compilers have taken on many of the abilities that were previously part of lint — especially the part where they check your code to ensure it’s type-safe. Early C compilers would let you write int foo = "hello"; and it would just blithely assign the pointer to the integer, and it was up to you to make sure you weren’t doing anything stupid. Modern C compilers complain loudly when you get your types wrong, and that’s a good thing.

Type Conflicts

So what’s all this got to do with the mysterious conflicting-type error on the line of the function declaration? As I said above, C compilers still have to either know or guess what a name means the first time they see that name as they scan forward through the file: They can know what it means it if it’s an actual function declaration itself (or a function «prototype,» more on that shortly), but if it’s just a call to the function, they have to guess. And, sadly, the guess is often wrong.

When the compiler saw your call to do_something(), it looked at how it was invoked, and it concluded that do_something() would eventually be declared like this:

int do_something(char arg1[], char arg2[])
{
    ...
}

Why did it conclude that? Because that’s how you called it! (Some C compilers may conclude that it was int do_something(int arg1, int arg2), or simply int do_something(...), both of which are even farther from what you want, but the important point is that regardless of how the compiler guesses the types, it guesses them differently from what your actual function uses.)

Later on, as the compiler scans forward in the file, it sees your actual declaration of char *do_something(char *, char *). That function declaration isn’t even close to the declaration that the compiler guessed, which means that the line where the compiler compiled the call was compiled wrong, and the program is just not going to work. So it rightly prints an error telling you that your code isn’t going to work as written.

You might be wondering, «Why does it assume I’m returning an int?» Well, it assumes that type because there’s no information to the contrary: printf() can take in any type in its variable arguments, so without a better answer, int is as good a guess as any. (Many early C compilers always assumed int for every unspecified type, and assumed you meant ... for the arguments for every function declared f() — not void — which is why many modern code standards recommend always putting void in for the arguments if there really aren’t supposed to be any.)

The Fix

There are two common fixes for the function-declaration error.

The first solution, which is recommended by many other answers here, is to put a prototype in the source code above the place where the function is first called. A prototype looks just like the function’s declaration, but it has a semicolon where the body should be:

char *do_something(char *dest, const char *src);

By putting the prototype first, the compiler then knows what the function will eventually look like, so it doesn’t have to guess. By convention, programmers often put prototypes at the top of the file, just under the #include statements, to ensure that they’ll always be defined before any potential usages of them.

The other solution, which also shows up in some real-world code, is to simply reorder your functions so that the function declarations are always before anything that calls them! You could move the entire char *do_something(char *dest, const char *src) { ... } function above the first call to it, and the compiler then would know exactly what the function looks like and wouldn’t have to guess.

In practice, most people use function prototypes, because you can also take function prototypes and move them into header (.h) files so that code in other .c files can call those functions. But either solution works, and many codebases use both.

C99 and C11

It is useful to note that the rules are slightly different in the newer versions of the C standard. In the earlier versions (C89 and K&R), the compiler really would guess the types at function-call time (and K&R-era compilers often wouldn’t even warn you if they were wrong). C99 and C11 both require that the function declaration/prototype must precede the first call, and it’s an error if it doesn’t. But many modern C compilers — mainly for backward compatibility with earlier code — will only warn about a missing prototype and not consider it an error.

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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
//Данная программа используется для учета поступлений из-за границы
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <locale.h>
#include <stdbool.h>
#include "menu.h"
 
//Описание функции которые были использованы в программе
void sozd();
void prosm();
void dobav();
void ydalponom();
void redakPoNom();
void dwoich ();
void prosmdw ();
void vrem ();
 
int menu(int kp, char* nazv[]);
//Описание структуры
struct perevodi
{
    char fio[30];
    char date[30];
    char sum[30];
    int countEl;
 
} mas[30], tmp;
//Глобальная переменная для хранения кол-ва элементов в массиве
int N = 0;
 
 
 
 
void main() {
    //Устанавливаем русский язык для корректного отображения меню и других надписей.
    //Данная установка не действует на введенные данные. Информацию следует вводить на английском языке без пробелов.
    setlocale(LC_ALL, "RUS");
    //Описание элементов для меню
    int kp = 9, nom;
    char *nazv[] = { "Создание файла", "Добавление записи в файл", "Редактировать строку по номеру в файле",
        "Просмотр данных", "Удалить строку по номеру в файле", "Запись в двоичном виде", "Просмотр в двоичном", "Учет времени", "Выход" };
 
    //Работа с меню. Мы получаем пункт меню от пользователя и вызываем соответствующую функцию
    while (1)
    {
        system("cls");
        nom = menu(kp, nazv);
        switch (nom)
        {
        case 1:sozd(); break;
        case 2:dobav(); break;
        case 3:redakPoNom(); break;
        case 4:prosm(); break;
        case 5:ydalponom(); break;
        case 6:dwoich (); break;
        case 7:prosmdw (); break;
        case 8: vrem (); break;
        case 9:return;
        }
    }
}
 
//Данная функция служит для вывода элементов меню на экран, а также для получения номера пункта который выбрал пользователь
int menu(int kp, char *nazv[])
{
    int i, nomer;
    //Вывод элементов
    for (i = 0; i<kp; i++)
        printf("%d.%sn", i + 1, nazv[i]);
    printf("nn Выбери пункт меню->  ");
    //Получение номера
    scanf("%d", &nomer);
    return nomer;
}
 
//Данная функция открывает файл (или создает если такого файла не сущ.) и заполняет его содержимым, который ввел пользователь
void sozd()
{
    //Создание и открытие файла
    FILE *p;
    p = fopen("el.txt", "wt");
    // Очистка консоли
    system("cls");
    //Ввод данных до тех пор, пока пользователь не введет * вместо имени
    while (1)
    {
        //Считывание данных с консоли и запись их в структурную переменную tmp
        printf("Ввести фамлию пользователя * для выхода -> ");
        scanf("%s", tmp.fio);
        if (tmp.fio[0] == '*')
        {
            fclose(p);
            return;
        }
        printf("n Введите сумму, которую перевели-> ");
        scanf("%s", tmp.sum);
        printf("n Дата перевода-> ");
        scanf("%s", tmp.date);
        printf("n Введите кол-во переводов -> ");
        scanf("%d", &tmp.countEl);
 
        //Запись данных в файл
        fprintf(p, " %s", tmp.fio);
        fprintf(p, " %s", tmp.sum);
        fprintf(p, " %s", tmp.date);
        fprintf(p, " %dn", tmp.countEl);
 
 
    }
}
 
void dwoich ()
{
     //Создание и открытие файла
    FILE *p;
    p = fopen("dwoich.txt", "wb");
    // Очистка консоли
    system("cls");
    //Ввод данных до тех пор, пока пользователь не введет * вместо имени
    while (1)
    {
        //Считывание данных с консоли и запись их в структурную переменную tmp
        printf("Ввести фамлию пользователя * для выхода -> ");
        scanf("%s", tmp.fio);
        if (tmp.fio[0] == '*')
        {
            fclose(p);
            return;
        }
        printf("n Введите сумму, которую перевели-> ");
        scanf("%s", tmp.sum);
        printf("n Дата перевода-> ");
        scanf("%s", tmp.date);
        printf("n Введите кол-во переводов -> ");
        scanf("%d", &tmp.countEl);
 
        //Запись данных в файл
        fprintf(p, " %s", tmp.fio);
        fprintf(p, " %s", tmp.sum);
        fprintf(p, " %s", tmp.date);
        fprintf(p, " %dn", tmp.countEl);
 
}
}
//Данная функция предназначена для просмотра данных из файла
void prosm()
{
    FILE *p;
    system("cls");
    p = fopen("el.txt", "r");
    //Выводится шапка таблицы
    int sortir();
    printf("n----------------------------------------------------------------------------");
    printf("n| Номер |  Фамилия пользователя  |  Сумма  |     Дата    | Кол-во переводов |");
    printf("n----------------------------------------------------------------------------");
    int i = 0;
    //Считывание данных в массив до тех пор пока не дойдем до конца файла
    while (!feof(p)) {
 
        fscanf(p, "%s %s %s %d", mas[i].fio, mas[i].sum, mas[i].date, &mas[i].countEl);
        i++;
 
 
    }
    //Вывод данных из массива на экран
    for (int j = 0; j < i - 1; j++) {
        printf("n %6d | %22s | %7s | %9s |  %15d | ", j + 1, mas[j].fio, mas[j].sum, mas[j].date, mas[j].countEl);
    }
    printf("n-----------------------------------------------------------------------------");
    _getch();
    fclose(p);
}
 
void prosmdw()
{
    FILE *p;
    system("cls");
    p = fopen("dwoich.txt", "r+b");
    //Выводится шапка таблицы
    int sortir();
    printf("n----------------------------------------------------------------------------");
    printf("n| Номер |  Фамилия пользователя  |  Сумма  |     Дата    | Кол-во переводов |");
    printf("n----------------------------------------------------------------------------");
    int i = 0;
    //Считывание данных в массив до тех пор пока не дойдем до конца файла
    while (!feof(p)) {
 
        fscanf(p, "%s %s %s %d", mas[i].fio, mas[i].sum, mas[i].date, &mas[i].countEl);
        i++;
 
 
    }
    //Вывод данных из массива на экран
    for (int j = 0; j < i - 1; j++) {
        printf("n %6d | %22s | %7s | %9s |  %15d | ", j + 1, mas[j].fio, mas[j].sum, mas[j].date, mas[j].countEl);
    }
    printf("n-----------------------------------------------------------------------------");
    _getch();
    fclose(p);
}
 
//Данная функция предназначена для добавления данных в конец файл. Она работает практически также как функция sozd().
void dobav() {
    FILE *p;
    p = fopen("el.txt", "at");
    system("cls");
    //Ввод данных которые мы хотим дабавить с клавиатуры
    while (1)
    {
        printf("Ввести фамилию пользователя * для выхода -> ");
        scanf("%s", tmp.fio);
        if (tmp.fio[0] == '*')
        {
            fclose(p);
            return;
        }
        printf("n Введи сумму, который перевели-> ");
        scanf("%s", tmp.sum);
        printf("n Дата -> ");
        scanf("%s", tmp.date);
        printf("n Введите кол-во переводов -> ");
        scanf("%d", &tmp.countEl);
        //Добавление записи в конец файла
        fprintf(p, " %s", tmp.fio);
        fprintf(p, " %s", tmp.sum);
        fprintf(p, " %s", tmp.date);
        fprintf(p, " %dn", tmp.countEl);
 
        printf("nn Запись добавленаn ");
        _getch();
 
    }
 
}
//Данная функция предназначена для удаления записи по номеру строки в файле
void ydalponom() {
 
    system("cls");
    //Ввод номера удаляемой записи
    printf("nВведите номер удаляемой строки в файле   ");
    int nom;
    scanf("%d", &nom);
    FILE *p;
    system("cls");
    p = fopen("el.txt", "r");
 
    int i = 0;
    //Считывание данных из файла в массив
    while (!feof(p)) {
 
        fscanf(p, "%s %s %s %d", mas[i].fio, mas[i].sum, mas[i].date, &mas[i].countEl);
        i++;
    }
    freopen("el.txt", "wt", p);
    // Запись данных из массива обратно в файл. Записываются все строки кроме той, что нужно удалить
    for (int j = 0; j < i - 1; j++) {
        if (j != (nom - 1)) {
            fprintf(p, " %s", mas[j].fio);
            fprintf(p, " %s", mas[j].sum);
            fprintf(p, " %s", mas[j].date);
            fprintf(p, " %dn", mas[j].countEl);
 
        }
 
    }
    printf("n Запись удалена ");
    _getch();
    fclose(p);
}
 
//Данная функция служит для редактирования выбранной записи
void redakPoNom() {
    system("cls");
    //Получение номера записи для редактирования
    printf("nВведите номер редактируемой строки в файле   ");
    int nom;
    scanf("%d", &nom);
    FILE *p;
    system("cls");
    p = fopen("el.txt", "r");
 
    int i = 0;
    //Запись данных из файла в массив
    while (!feof(p)) {
 
        fscanf(p, "%s %s %s %d", mas[i].fio, mas[i].sum, mas[i].date, &mas[i].countEl);
        i++;
    }
 
    printf("nВведите новые значения этой строки n");
 
    //Занесение новых данных в редактируемую запись.
    // индекс nom-1 используется в связи с тем, что нумерация массива идет с 0, а в выводе данных для пользователя первая запись имеет номер 1
    printf("nВвести фамилию -> ");
    scanf("%s", mas[nom - 1].fio);
    printf("n Введи сумму -> ");
    scanf("%d", mas[nom - 1].sum);
    printf("n Дата -> ");
    scanf("%s", mas[nom - 1].date);
    printf("n Введите кол-во переводов -> ");
    scanf("%d", &mas[nom - 1].countEl);
 
    freopen("el.txt", "wt", p);
    //Запись обнавленных данных из массива в файл
    for (int j = 0; j < i - 1; j++) {
 
        fprintf(p, " %s", mas[j].fio);
        fprintf(p, " %s", mas[j].sum);
        fprintf(p, " %s", mas[j].date);
        fprintf(p, " %dn", mas[j].countEl);
 
 
 
    }
 
    printf("n Запись изменена ");
    _getch();
    fclose(p);
    }
 
void vrem ()
{
    int time;
}

07-25-2011


#1

solarbit is offline


Registered User


error: conflicting types for ‘functions’

Hi,

I’m trying to figure out what I did wrong here; the function Jacobi_Cyclic_Method is something I get from one of the math forum, I’m trying to make it work with my program but I keep getting this error

readfile2.c:69: error: conflicting types for ‘Jacobi_Cyclic_Method’
readfile2.c:46: error: previous implicit declaration of ‘Jacobi_Cyclic_Method’ was here

Can somebody point out to me, what exactly is wrong?

Code:

#include <stdio.h>
#include <string.h>
#include <float.h>                           // required for DBL_EPSILON
#include <math.h>                            // required for fabs()


main(void)
{
   #define N 2
    double eigenvalues[N], eigenvectors[N][N],A[N][N];
    int i, j,k,n=2;
    float cxx, cxy, cyx, cyy;
    FILE  *fp;
    char filename[32]="covariance_value.txt";


    for(i=0; i<2; i++)
    {
        for(j=0; j<2; j++)
        {
            A[i][j] = 0.0;
        }
    }

    if((fp=fopen(filename,"r+"))==NULL)
    {
        printf("cannot open the input file %sn",filename);
    }
    else
    {
        for(j=0; j<1; j++)
        {
            i = 2*j;
            fscanf(fp,"%f %f %f %f n", &cxx, &cxy, &cyx, &cyy);

            A[i][i]   = cxx;
            A[i][i+1] = cxy;
            A[i+1][i] = cyx;
            A[i+1][i+1] = cyy;

            printf("point #%d: Cxx = %f, Cxy = %f, Cyx = %f, Cyy = %fn",j,cxx,cxy,cyx,cyy);
        }
    }


      Jacobi_Cyclic_Method(eigenvalues,eigenvectors,A, N);

/*	for (k = 0;k< N; k++)
        {
		printf("EIGEN[%d]: %fn", k, eigenvalues[k]);
	}


	for (k = 0; k<N;k++)
        {
		printf("EIGENVEC[%d]:", k);
		for (j=0;j<N;j++)
                {
			printf(" %f", eigenvectors[k][j]);
		}
		printf("n");
	}
*/
   fclose(fp);
}


void Jacobi_Cyclic_Method(double eigenvalues[], double *eigenvectors,double *A, int n)
{
   int row, i, j, k, m;
   double *pAk, *pAm, *p_r, *p_e;
   double threshold_norm;
   double threshold;
   double tan_phi, sin_phi, cos_phi, tan2_phi, sin2_phi, cos2_phi;
   double sin_2phi, cos_2phi, cot_2phi;
   double dum1;
   double dum2;
   double dum3;
   double r;
   double max;

                  // Take care of trivial cases

   if ( n < 1) return;
   if ( n == 1) {
      eigenvalues[0] = *A;
      *eigenvectors = 1.0;
      return;
   }

          // Initialize the eigenvalues to the identity matrix.

   for (p_e = eigenvectors, i = 0; i < n; i++)
      for (j = 0; j < n; p_e++, j++)
         if (i == j) *p_e = 1.0; else *p_e = 0.0;

            // Calculate the threshold and threshold_norm.

   for (threshold = 0.0, pAk = A, i = 0; i < ( n - 1 ); pAk += n, i++)
      for (j = i + 1; j < n; j++) threshold += *(pAk + j) * *(pAk + j);
   threshold = sqrt(threshold + threshold);
   threshold_norm = threshold * DBL_EPSILON;
   max = threshold + 1.0;
   while (threshold > threshold_norm) {
      threshold /= 10.0;
      if (max < threshold) continue;
      max = 0.0;
      for (pAk = A, k = 0; k < (n-1); pAk += n, k++) {
         for (pAm = pAk + n, m = k + 1; m < n; pAm += n, m++) {
            if ( fabs(*(pAk + m)) < threshold ) continue;

                 // Calculate the sin and cos of the rotation angle which
                 // annihilates A[k][m].

            cot_2phi = 0.5 * ( *(pAk + k) - *(pAm + m) ) / *(pAk + m);
            dum1 = sqrt( cot_2phi * cot_2phi + 1.0);
            if (cot_2phi < 0.0) dum1 = -dum1;
            tan_phi = -cot_2phi + dum1;
            tan2_phi = tan_phi * tan_phi;
            sin2_phi = tan2_phi / (1.0 + tan2_phi);
            cos2_phi = 1.0 - sin2_phi;
            sin_phi = sqrt(sin2_phi);
            if (tan_phi < 0.0) sin_phi = - sin_phi;
            cos_phi = sqrt(cos2_phi);
            sin_2phi = 2.0 * sin_phi * cos_phi;
            cos_2phi = cos2_phi - sin2_phi;

                     // Rotate columns k and m for both the matrix A
                     //     and the matrix of eigenvectors.

            p_r = A;
            dum1 = *(pAk + k);
            dum2 = *(pAm + m);
            dum3 = *(pAk + m);
            *(pAk + k) = dum1 * cos2_phi + dum2 * sin2_phi + dum3 * sin_2phi;
            *(pAm + m) = dum1 * sin2_phi + dum2 * cos2_phi - dum3 * sin_2phi;
            *(pAk + m) = 0.0;
            *(pAm + k) = 0.0;
            for (i = 0; i < n; p_r += n, i++) {
               if ( (i == k) || (i == m) ) continue;
               if ( i < k ) dum1 = *(p_r + k); else dum1 = *(pAk + i);
               if ( i < m ) dum2 = *(p_r + m); else dum2 = *(pAm + i);
               dum3 = dum1 * cos_phi + dum2 * sin_phi;
               if ( i < k ) *(p_r + k) = dum3; else *(pAk + i) = dum3;
               dum3 = - dum1 * sin_phi + dum2 * cos_phi;
               if ( i < m ) *(p_r + m) = dum3; else *(pAm + i) = dum3;
            }
            for (p_e = eigenvectors, i = 0; i < n; p_e += n, i++) {
               dum1 = *(p_e + k);
               dum2 = *(p_e + m);
               *(p_e + k) = dum1 * cos_phi + dum2 * sin_phi;
               *(p_e + m) = - dum1 * sin_phi + dum2 * cos_phi;
            }
         }
         for (i = 0; i < n; i++)
            if ( i == k ) continue;
            else if ( max < fabs(*(pAk + i))) max = fabs(*(pAk + i));
      }
   }
   for (pAk = A, k = 0; k < n; pAk += n, k++) eigenvalues[k] = *(pAk + k);
}


When you’re compiling a C program using GCC, you sometimes run into a compilation error that says “error: conflicting Types for ‘function.’” The definition of a function is not consistent with the declaration.

(a) First, let’s take a look at an example where the definition and declaration of a function are inconsistent:

#include <stdio.h>

int func(int a);

int func(void) {
    return 0;
}

int main(void) {

    func();

    return 0;
}

Compiler:

gcc -g -o a a.c
a.c:5:5: error: conflicting types for ‘func’
 int func(void) {
     ^
a.c:3:5: note: previous declaration of ‘func’ was here
 int func(int a);

You can see that this error occurs at compile time because the declaration and definition of “func” are inconsistent (one with arguments and one without).
(b) Recently, when I ported some code to JFFS2, this error also occurred at compile time. But I found that the declaration and definition of the function in the header file were exactly the same, which surprised me. The conclusion is that the function parameter type is defined after the function is declared. The simplified code is as follows:

#include <stdio.h>

void func(struct A *A);

struct A {
        int a;
};

void func(struct A *A)
{
        printf("%d", A->a);
}

int main(void) {
        // your code goes here
        struct A a = {4};
        func(&a);
        return 0;
}

Where the definition of “structure A” is placed after the “func” function declaration, and the func function argument is the “structure A*” type. The compilation results are as follows:

gcc -g -o a a.c
a.c:3:18: warning: ‘struct A’ declared inside parameter list
 void func(struct A *A);
                  ^
a.c:3:18: warning: its scope is only this definition or declaration, which is probably not what you want
a.c:9:6: error: conflicting types for ‘func’
 void func(struct A *A)
      ^
a.c:3:6: note: previous declaration of ‘func’ was here
 void func(struct A *A);
      ^

You can also see the output error “error: Conflicting Types for ‘func’”. Perhaps a compilation warning is a clue.

Read More:

I’m trying to write a basic practice with C, working with Binary and Hex. I made a method to print the multiples of 2 (powers of 2) and a separate method to print out the Hex form of that multiple of 2.

#include <stdlib.h>
#include <stdio.h>

const char one = 1;
const int bits = 31;

void    print2       ()
{
    unsigned int  u = (int)one;
    unsigned int j;

    printf("The powers of 2 are:n");

    for(j=0;j<bits;j++)
    {
            unsigned int temp = u<<j;
            printf("%dn",abs(temp));
            printhex(temp);
    }

    printf("nn");
}

void    printhex       (unsigned int   u)
{
    printf("0x%08Xn",u);
}

int main ()
{
    print2();
    return(EXIT_SUCCESS);
}

What I don’t understand is why I get an error «conflicting types» from calling on the method «printHex». I specifically ask for an unsigned integer and when I call the method within the parameter (which I assume to be unsigned integer «temp»), the compiler does not accept.


You run into problems because you’ve not provided a prototype for printhex() before you use it.

Either put printhex() physically before print2() in the source file, or add a declaration:

extern void printhex(unsigned int u);

before print2() is defined. (Don’t declare printhex() inside print2(); even though it is syntactically legal, it is bad practice to do so.)


When the compiler runs across the call printhex(temp), it assumes (under C89 rules) that it is a function that returns an int with an indeterminate argument list (but not one which is formally a variable argument list — varargs functions like printf() must always have a prototype in scope). When you subsequently define it as returning void, it gets upset and reports the conflicting type error. Under C99 rules, you are supposed to have a prototype in scope before using a function.

I’d like to comment on your layout; it’s a little unorthodox.

The function definitions don’t need as many blanks in them (use less white space in the function definitions):

void    print2       ()
void    printhex       (unsigned int   u)

would be:

void print2(void)
void printhex(unsigned int u)

if I were writing them. I write functions with the explicit (void) in the definition so it matches the prototype notation for the function. Actually, if I was writing them, they’d more likely be prefixed with static. If the function I write is not going to be used outside the source file it is in, then I make it static automatically. Further, if the function is defined as static before it is used, then I don’t need a second declaration of the function. If a function is not static, there should, in my book, be a header that declares the function, and that header should be used in both the file that defines the function and in the files that use the function. This ensures consistency.

Also, you use abs(temp) which is slightly odd; it is a long-winded way of converting the unsigned int to a signed int, but you’d do better to write:

 printf("%un", temp);

Finally, I’d suggest you use more white space in the for loop:

for (j = 0; j < bits; j++)

No space before commas or semicolons; spaces around binary operators (but not unary operators, or very tightly binding operators such as subscripts or member (. or ->) operators).

Your output interleaves hex with decimal; you might find it better to use:

printf("%10u ", temp);

to put the decimal value right justified on the line, leaving the hex to appear after it on the same line.

Thread: error: conflicting types for ‘functions’

Thread Tools
Search Thread
Display

error: conflicting types for ‘functions’

I’m trying to figure out what I did wrong here; the function Jacobi_Cyclic_Method is something I get from one of the math forum, I’m trying to make it work with my program but I keep getting this error

readfile2.c:69: error: conflicting types for ‘Jacobi_Cyclic_Method’
readfile2.c:46: error: previous implicit declaration of ‘Jacobi_Cyclic_Method’ was here

Can somebody point out to me, what exactly is wrong?

The hint is in the error message: «implicit declaration». If you use a function without declaring it, well, that’s illegal in C99; in C89 you were allowed to do so if every parameter, and the return type, were of type int. Since that isn’t true, you’re not allowed to do so.

You need to prototype the function.

Also note:
1) The correct form of main is int main (void) and it returns a value (usually 0 or an error number) to the operating system.
2) Scoop and Poop code is not the way to learn C programming. all it does is teach you to rely upon other people’s good work.

Источник

Member Avatar

13 Years Ago

I have been coding for a little bit in VB mostly and decided to try C right all is dandy until I try using a function

I am getting a conflicting types error in function encrypt

here is my beautiful code

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[])
{
  /* Declaring the functions */
  char encrpyt(int , char);
  
  int key = 5;
  char string[81];
  
  gets(string);
  
  encrypt(key , string);
  
  system("PAUSE");	
  return 0;
}


char encrypt(int codekey, char stringydoo[80] ) /* Encrypt Header line */
{
      int i,stringnums[80];
      
      for(i=0; i<80; i++)
      {
           stringnums[i] = stringydoo[i];
           if (stringnums[i]>=32 && stringnums[i]<=126)
           {
                               
                               stringnums[i] = stringnums[i]+ codekey;
                                                  
                                                  if (stringnums[i]>=126)
                                                  {
                                                                           stringnums[i] = 32 + (stringnums[i]%126);
                                                  }
                                                                           
           stringydoo[i] = stringnums[i];
           }
           
  
      }

      
      puts(stringydoo);
      system("PAUSE");
}

this is the exact errors from bloodshed

21 xxxxmain.c conflicting types for ‘encrypt’
13 xxxxmain.c previous implicit declaration of ‘encrypt’ was here

Edited

13 Years Ago
by Sapreaver because:

adding the error.


Recommended Answers

check line #6:

char encrpyt(int , char);

the parameters are int and char.
In line #20

char encrypt(int codekey, char stringydoo[80] ) /* Encrypt Header line */

now the params are one int and a char [].

correct the prototype at line #6.

Jump to Post

try making your declaration before main (not inside main)

Jump to Post

hi there is already one library method in unistd.h called encrypt() hence it is giving the problem.
Change the function name to something else like encryptit().
It should work.

Jump to Post

All 9 Replies

Member Avatar

13 Years Ago

I have been trying things for about 3-hours I think I have tried everything :/

Member Avatar


dkalita

110



Posting Pro in Training


13 Years Ago

check line #6:

char encrpyt(int , char);

the parameters are int and char.
In line #20

char encrypt(int codekey, char stringydoo[80] ) /* Encrypt Header line */

now the params are one int and a char [].

correct the prototype at line #6.

Member Avatar

13 Years Ago

check line #6:

char encrpyt(int , char);

the parameters are int and char.
In line #20

char encrypt(int codekey, char stringydoo[80] ) /* Encrypt Header line */

now the params are one int and a char [].

correct the prototype at line #6.

I changed

char encrpyt(int , char);

to

char encrpyt(int , char[80]);

to match the version on the function header both ways

when I removed all mention of an array from the main function I still got the error so I changed the code like so

{
  /* Declaring the functions */
  void encrpyt(int , char);
  
  int key = 5;
  char string;
  
  
  encrypt(key , string);
  
  system("PAUSE");	
  return 0;
}


void encrypt(int codekey, char stringydoo) /* Encrypt Header line */

and I still have the error

Member Avatar


dkalita

110



Posting Pro in Training


13 Years Ago

try making your declaration before main (not inside main)

Member Avatar

13 Years Ago

Same thing. right now the prototype is

void encrpyt(int , char []);

string is defined like

char string[81]

the pass is

encrypt(key , string);

The function header is

void encrypt(int codekey, char spots[])

Member Avatar

dkalita

110



Posting Pro in Training


13 Years Ago

hi there is already one library method in unistd.h called encrypt() hence it is giving the problem.
Change the function name to something else like encryptit().
It should work.

Member Avatar

Member Avatar


dkalita

110



Posting Pro in Training


13 Years Ago

still nothing

hi, i tried the following program in my pc and it compiled successfully.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{

  char encryptit(int x, char c[80]);

  int key = 5;
  char string[81];

  gets(string);

  encryptit(key , string);

  system("PAUSE");
  return 0;
}

char encryptit(int codekey, char stringydoo[80] ) /* Encrypt Header line */
{
      int i,stringnums[80];

      for(i=0; i<80; i++)
      {
           stringnums[i] = stringydoo[i];
           if (stringnums[i]>=32 && stringnums[i]<=126)
           {

                               stringnums[i] = stringnums[i]+ codekey;

                                                  if (stringnums[i]>=126)
                                                  {
                                                                           stringnums[i] = 32 + (stringnums[i]%126);
                                                  }

           stringydoo[i] = stringnums[i];
           }


      }


      puts(stringydoo);
      system("PAUSE");
}

Member Avatar

13 Years Ago

hi, i tried the following program in my pc and it compiled successfully.

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{

  char encryptit(int x, char c[80]);

  int key = 5;
  char string[81];

  gets(string);

  encryptit(key , string);

  system("PAUSE");
  return 0;
}

char encryptit(int codekey, char stringydoo[80] ) /* Encrypt Header line */
{
      int i,stringnums[80];

      for(i=0; i<80; i++)
      {
           stringnums[i] = stringydoo[i];
           if (stringnums[i]>=32 && stringnums[i]<=126)
           {

                               stringnums[i] = stringnums[i]+ codekey;

                                                  if (stringnums[i]>=126)
                                                  {
                                                                           stringnums[i] = 32 + (stringnums[i]%126);
                                                  }

           stringydoo[i] = stringnums[i];
           }


      }


      puts(stringydoo);
      system("PAUSE");
}

Thank you very much for helping me, I see what I was doing wrong when I compared the two now. :/ Thank you for the spoon feed. I now have a new goal. To keep at it until I get it.


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

Быстрая починка:

Убедитесь, что ваши функции объявлены один раз и только один раз перед их вызовом. Например, изменить:

main(){ myfun(3.4); }
double myfun(double x){ return x; }

В:

double myfun(double x){ return x; }
main(){ myfun(3.4); }

Или добавьте отдельное объявление функции:

double myfun(double x);
main(){ myfun(3.4); }
double myfun(double x){ return x; }

Возможные причины ошибки

  1. Функция была вызвана до объявления
  2. Определенная функция переопределяет функцию, объявленную во включенном заголовке.
  3. Функция была определена дважды в одном и том же файле
  4. Декларация и определение не совпадают
  5. Конфликт объявлений во включенных заголовках

Что на самом деле происходит

error: conflicting types for ‘foo’ означает, что функция была определена более одного раза с разными сигнатурами типов.

Файл, содержащий две функции с одинаковыми именами, но разными типами возвращаемых данных, вызовет эту ошибку, например:

int foo(){return 1;}
double foo(){return 1.0;}

Действительно, при компиляции с помощью GCC мы получаем следующие ошибки:

foo.c:5:8: error: conflicting types for ‘foo’
 double foo(){return 1.0;}
        ^
foo.c:4:5: note: previous definition of ‘foo’ was here
 int foo(){return 1;}
     ^

Теперь, если бы вместо этого у нас был файл с двумя определениями функций с одинаковым именем

double foo(){return 1;}
double foo(){return 1.0;}

Вместо этого мы получили бы ошибку «переопределения»:

foo.c:5:8: error: redefinition of ‘foo’
 double foo(){return 1.0;}
        ^
foo.c:4:8: note: previous definition of ‘foo’ was here
 double foo(){return 1;}
        ^

Неявное объявление функции

Итак, почему следующий код выдает error: conflicting types for ‘foo’?

 main(){ foo(); }
 double foo(){ return 1.0; }

Причина в неявное объявление функции.

Когда компилятор впервые встречает foo() в main функция, она примет сигнатуру типа для функции foo of int foo(). По умолчанию предполагается, что неявные функции возвращают целые числа, а типы входных аргументов являются производными от того, что вы передаете в функцию (в данном случае ничего).

Очевидно, что компилятор ошибается, делая такое предположение, но спецификации для языка C (и, следовательно, Objective-C) старые, капризные и не очень умные. Возможно, когда-то неявное объявление функций сэкономило время разработки, уменьшив сложность компилятора, но теперь мы застряли с ужасной функцией, которая никогда не должна была быть реализована в языке. Фактически неявные объявления были объявлены незаконными в C99.

Тем не менее, как только вы узнаете, что происходит, вам будет легко найти основную причину вашей проблемы.

#include <stdbool.h>
#include <stdio.h>
#include "bst.h"
 
void PKL(BstNode **node, const int level);

int main(void)
{
    int i, maxBFS;
    char cmd[255], arg;
    BstNode *root = NULL;
 
    do
    {
        printf("Введите команду (h - справка):n");
        scanf("%s", cmd);
 
        if (cmd[0] == '+')
        {
            scanf(" %c", &arg);
 
            if (arg >= 'A' && arg <= 'Z')
            {
                bstInsert(&root, arg);
 
                printf("Узел %c вставленn", arg);
            }
            else
                printf("Ошибка. Введена недопустимая букваn");
        }
        else if (cmd[0] == '-')
        {
            scanf(" %c", &arg);
 
            if (arg >= 'A' && arg <= 'Z')
            {
                if (bstRemove(&root, arg))
                    printf("Узел %c удаленn", arg);
                else
                    printf("Узел %c не найденn", arg);
            }
            else
                printf("Ошибка. Введена недопустимая букваn");
        }
        else if (cmd[0] == 'p')
        {
            PKL(&root, 0);
        }
        
        else if (cmd[0] == 't')
        {
         if (is_symmetric(&root))
         {
            printf("YES");
         }
            else
            {
            printf("NO");   
            }   
            }   
        else if (cmd[0] == 'h')
        {
            printf("================================n");
            printf("Список команд:n");
            printf("+ CHAR - вставить узел CHAR (A, B, ..., Z) в двоичное деревоn");
            printf("- CHAR - удалить узел CHAR из двоичного дереваn");
            printf("p - распечатать двоичное деревоn");
            printf("t - выполнить задание над двоичным деревомn");
            printf("q - завершить программуn");
            printf("================================n");
        }
        else if (cmd[0] != 'q')
        {
            printf("Неизвестная командаn");
        }
    }
    while (cmd[0] != 'q');
 
    bstDestroy(&root);
 
    return 0;
}
void PKL(BstNode **node, const int level)
{
    if (*node == NULL)
    {
        printf("Дерево пустоn");
 
        return;
    }
 
    if ((*node)->_right != NULL)
        PKL(&(*node)->_right, level + 1);
 
    printf("%*s%cn", level * 2, "", (*node)->_key);
 
    if ((*node)->_left != NULL)
        PKL(&(*node)->_left, level + 1);
}

_Bool mirror_equals(BstNode *_left, BstNode *_right)
{
    if( _left == NULL || _right == NULL )
        {return _left == NULL && _right == NULL;
    return (_left->_key == _right->_key &&
        mirror_equals(_left->_left, _right->_right) &&
        mirror_equals(_left->_right, _right->_left) );}
}
_Bool is_symmetric(BstNode *node)
{
    if( node == NULL|| mirror_equals(node->_left, node->_right))
        {return true;}
    else {return false;}
}
3.c:111:7: error: conflicting types for ‘is_symmetric’
 _Bool is_symmetric(BstNode *node)
       ^
3.c:53:8: note: previous implicit declaration of ‘is_symmetric’ was here
    if (is_symmetric(&root))
        ^

Понравилась статья? Поделить с друзьями:
  • Error configuring openssl
  • Error constant expression required java
  • Error configuring autostart
  • Error confidence value memtest
  • Error confidence value 227