0

I have three simple files that I have trouble compiling for some reason. When I use the terminal to compile the program (g++ .\main.cpp .\dynamic.cpp). I get this error message:

C:\Users\user1\AppData\Local\Temp\ccMPpwkX.o:main.cpp:(.text+0x4d): undefined reference to DynamicAr<int>::DynamicAr(int*, int)' C:\Users\user1\AppData\Local\Temp\ccMPpwkX.o:main.cpp:(.text+0x5a): undefined reference to DynamicAr::printAr()' collect2.exe: error: ld returned 1 exit status

main.cpp

#include "dynamic.h"

int main ()
{
    int arr[] = { 0, 1, 2, 3, 4 };
    DynamicAr<int> myArr(arr, 5);
    myArr.printAr();

    return 0;
}

dynamic.h

#ifndef DYNAMIC_H
#define DYNAMIC_H

#include <iostream>
#include <string>
using namespace std;

template <typename T>
class DynamicAr
{
private:
    T* dynamicAr;
    int size;

public:
    DynamicAr(T arr[], int size);
    void printAr();

};

#endif

dynamic.cpp

#include "dynamic.h"

template <typename T>
DynamicAr<T>::DynamicAr(T arr[], int size)
{
    dynamicAr = new T[size];
    this->size = size;
    
    for (int i = 0; i < size; i++)
    {
        dynamicAr[i] = arr[i];
    }
}

template <typename T>
void DynamicAr<T>::printAr()
{
    for (int i = 0; i < size; i++)
    {
        cout << *(dynamicAr + i) << endl;
    }
}

I have tried this exact code in Eclipse IDE and it works perfectly fine. I have also tried taking a look at the .json files but everything looks ok to me. The code should simply output the array contents.

tasks.json

{
    "tasks": [
        {
            "type": "cppbuild",
            "label": "C/C++: g++.exe build active file",
            "command": "C:\\MinGW\\bin\\g++.exe",
            "args": [
                "-fdiagnostics-color=always",
                "-g",
                "${file}",
                "-o",
                "${fileDirname}\\${fileBasenameNoExtension}.exe"
            ],
            "options": {
                "cwd": "${fileDirname}"
            },
            "problemMatcher": [
                "$gcc"
            ],
            "group": {
                "kind": "build",
                "isDefault": true
            },
            "detail": "Task generated by Debugger."
        }
    ],
    "version": "2.0.0"
}

c_cpp_properties.json

{
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                "${workspaceFolder}/**"
            ],
            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "compilerPath": "C:\\MinGW\\bin\\gcc.exe",
            "cStandard": "gnu17",
            "cppStandard": "gnu++14",
            "intelliSenseMode": "windows-gcc-x64"
        }
    ],
    "version": 4
}
Kaio-n
  • 1
  • 1

0 Answers0