0

Environment: MacOS

Compiler version: C++20

I'm new to C++, and I'm writing a ForceInit.h file, and call it in the MainFunc.cpp.

In ForceInit.h:

#ifndef FORCE_INIT_H
#  define FORCE_INIT_H

#include<iostream>
using namespace std;

namespace hw32 {
    struct ForceInit {
        ForceInit() {
            if (count == 0) {
                count = 1;
                ios_base::Init();
            }
        }
        private:
            static int count;
    };
    static ForceInit forceinit;
}

#endif

In MainFunc.cpp:

#include <iostream>
#include "forceinit.h"

using namespace std;
using namespace hw32;


// Driver Code
int main()
{
    return 0;
}

And it gives me error:

Build finished with errors(s):
Undefined symbols for architecture x86_64:
  "__ZN4hw329ForceInit5countE", referenced from:
      __ZN4hw329ForceInitC1Ev in ccGyt5tf.o
ld: symbol(s) not found for architecture x86_64

I would like to know what's wrong with the code in the header file.

IsaIkari
  • 1,002
  • 16
  • 31
  • There is nothing wrong with the code in the header file. The problem is missing code in main.cpp. You haven't defined `hw32::ForceInit::count` only declared it. Add the following to main.cpp `int hw32::ForceInit::count = 0;` – john Feb 04 '21 at 16:38
  • @john awesome! It works!! Thanks!! – IsaIkari Feb 04 '21 at 18:47

0 Answers0