如何修复C中未解决的外部错误

时间:2012-05-14 21:01:46

标签: c struct

当我在C中编译我的代码时,我收到以下错误“错误LNK2001:未解析的外部符号_staff”以及有关未解析的外部错误的错误。听起来它认为我的staff数组需要一个外部文件,但它只是一个用于持有Persons(两种类型的联盟)的数组。我该如何解决这个问题?我的代码的开头如下。

        #include <stdio.h>
        #include <string.h>
    //employee struct

        typedef struct {    
        //...
        } Employee;

    //Manager struct inheriting from employee struct

        typedef struct {
        Employee employee;   
        int bonus;
        } Manager;  

    //union of manager and employee

        typedef union{
           Employee e;
           Manager m;
          } Person;
    //functions

        Employee newEmployee(char n[], ...);    
        Manager newManager(...);
        double getManagerSalary(Manager man);    
        Manager boss; 
        Employee harry ;
        Employee tommy;
        Person staff[];

//main code

    int main(void)
    {

      boss = newManager(...);
      harry = newEmployee(...);       
      tommy = newEmployee(...);

      staff[3]; 
      staff[0].m = boss;
      staff[1].e = harry;
      staff[2].e = tommy;

     ...    
    }   

    Employee newEmployee(char n[], double s, int year, int month, int day)
    {
    ...
    }

2 个答案:

答案 0 :(得分:1)

必须在C中声明数组的大小为Eg:Person a[1],这意味着a is an array of 1 Person。你不能以你的方式声明它。

如果要在运行时尝试估计人数,请尝试使用指针。 Person *a然后考虑人员总数来分配记忆并继续但是我认为你不想这样做。

另请参阅@ShinTakezou的extern消息。它是一个重要而有效的观点,尽管与您的实施完全无关。

答案 1 :(得分:0)

        // you are not reserving room for anything;
        // gcc would give an error; your compiler silently consider this
        // staff as a pointer to something (an array) which has its actual
        // memory defined elsewhere; so, when you link, it raises that 
        // linking error
        Person staff[];

        // could be
        Person staff[N];
        // where N is a positive number, or a true define or const value

//main code

    int main(void)
    {

      boss = newManager(...);
      harry = newEmployee(...);       
      tommy = newEmployee(...);

      // the following line is an expresion which does nothing:
      // it accesses the fourth element of a "supposed" array,
      // and the value retrieved in this way is lost
      // if you meant to "allocate" three staff, you are doing it wrong; 
      staff[3]; 

      // following the possible previous path of having the 
      // room for staff not dynamically created, you don't need the
      // previous line, which is simply a no-op (if 3 is less than N-1, 
      // otherwise it's a potentially illegal access to memory you shouldn't access)

      staff[0].m = boss;
      staff[1].e = harry;
      staff[2].e = tommy;

     ...    
    }   

(我还补充一点,代码看起来并不完全“理智” - 不用说 - 给我,但这可能是另一个问题,与这个特定问题无关)< / p>