-1

コードを C でコンパイルすると、「エラー LNK2001: 未解決の外部シンボル _staff」というエラーと、未解決の外部に関するエラーが発生します。私のstaff配列には外部ファイルが必要だと思われているようですが、それはPersons(2つのタイプのUnion)を保持するための単なる配列です。問題を解決するにはどうすればよいですか? 私のコードの冒頭は以下です。

        #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)
    {
    ...
    }
4

2 に答える 2

1

配列のサイズをCで宣言する必要があります。たとえば、これは。Person a[1]を意味しa is an array of 1 Personます。あなたがしたようにそれを宣言することはできません。

実行時にPersonの数を見積もる場合は、ポインターを試してください。次に、人の総数を考慮してメモリを割り当てて続行しますPerson *aが、これは実行したくないと思います。

extern@ShinTakezouのメッセージもご覧ください。実装とはまったく関係ありませんが、これは重要で有効なポイントです。

于 2012-05-15T05:14:47.487 に答える
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;

     ...    
    }   

(また、コードが完全に「正気」に見えないことも付け加えます—おそらく言うまでもなく—私には、これはこの特定の問題とは関係のない別の質問の問題である可能性があります)

于 2012-05-15T17:02:09.820 に答える