كيف يمكن للإعلان أن يتعارض مع نفسه؟
سؤال
هذا هو الخطأ الذي أحصل عليه عند محاولة تجميع بعض التعليمات البرمجية التي تستخدم taucs (وليس الكود الخاص بي):
.../taucs/src/taucs.h:554: error: conflicting declaration ‘typedef struct taucs_ccs_matrix taucs_ccs_matrix’
.../taucs/src/taucs.h:554: error: ‘taucs_ccs_matrix’ has a previous declaration as ‘typedef struct taucs_ccs_matrix taucs_ccs_matrix’
وات؟ إنه متضارب مع نفسه؟
بعد أن قرأت نفسي ، قمت بإنشاء رأس اختبار ووضعت في تعريف متضارب ، فقط للتأكد من أنني كنت على صواب في هذا:
في ملف testit.h:
#include "somethingelse.h"
typedef struct
{
int n;
} foobar;
في ملف somethingelse.h:
typedef struct
{
int n;
} foobar;
بالتأكيد ، أحصل على:
testit.h:6: error: conflicting declaration ‘typedef struct foobar foobar’
somethingelse.h:4: error: ‘foobar’ has a previous declaration as ‘typedef struct foobar foobar’
أو إذا كان لدي هذا في testit.h:
typedef struct
{
int n;
} foobar;
typedef struct
{
int n;
} foobar;
testit.h:9: error: conflicting declaration ‘typedef struct foobar foobar’
testit.h:4: error: ‘foobar’ has a previous declaration as ‘typedef struct foobar foobar’
يختلف رقم السطر دائمًا - لا يمكن أن يتعارض الإعلان مع نفسه. انا لم احصل عليها. أي شخص رأى هذا من قبل؟
المحلول
هل يمكن أن يكون ملف رأسك (.../taucs/src/taucs.h
) ، الذي يحتوي على الإعلان ، يتم تضمينه (بشكل مباشر أو غير مباشر) مرتين من قبل اثنين #include
التوجيهات؟
نصائح أخرى
هل يتم تضمين الرأس الفردي في ملفات مصدر متعددة؟ إذا كان الأمر كذلك ، فأنت بحاجة إلى لفه في "تضمين حراس" مثل ذلك:
#ifndef TAUCS_H
#define TAUCS_H
//Header stuff here
#endif //TAUCS_H
typedef struct
{
int n;
} foobar;
typedef struct
{
int n;
} foobar;
testit.h:9: error: conflicting declaration ‘typedef struct foobar foobar’
testit.h:4: error: ‘foobar’ has a previous declaration as ‘typedef struct foobar foobar’
في هذا المثال ، تعطي 2 إعلانات من Foobar. لا يعرف المترجم أي واحد يختار - لذلك ينقذ إعلان متضارب. لا يمكنك إعلان نفس الشيء مرتين.
لا تكرر التعريف. يسمح C ++ بتعريف الظهور مرة واحدة فقط. ما يمكنك فعله هو تكرار الإعلان.
أ typedef
هو دائما تعريف. لذا فإن أول شيء أوصي به هو إعطاء struct
اسم مناسب (وبما أن هذا C ++ ، فإن typedef لا يضيف أي فائدة ، لذا فقط قم بإسقاط typedef):
// file1.h
struct foobar
{
int n;
};
بعد ذلك ، يجب أن يكون ذلك في ملف واحد بالضبط. إذا كان لديك ملفات لا تستخدم فقط مؤشرات إلى Foobar ، فيمكنك كرر الإعلان (ليس فقط التعريف):
// file2.h
// This is just a declaration so this can appear as many times as
// you want
struct foobar;
void doit(const foobar *f);
لقد واجهت نفس المشكلة التي تربط الكود الخاص بي وكان الأمر كذلك ليس إعلان مزدوج من النوع. اشتكى PC-Lint من نفس typedef المستخدمة في رمز C ++ المختلط. يمكنني إصلاح ذلك من خلال تجنب نفس الإعلان في ج و ملفات C ++. أتمنى أن يساعد ذلك شخص ما.