You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++类成员未定义引用错误求助:疑似编译方式导致的问题排查

Fixing the "undefined reference to Test::Test()" Linker Error

Hey there! I totally get how frustrating it is when you know the issue ties back to your build process but can't nail down the exact problem. Let's break this down and fix that annoying error step by step.

The Root Cause

First off, that's a linker error, not a compiler error. Your compiler successfully processed main.cpp, but when the linker tried to assemble all the pieces, it couldn't find the actual implementation of Test::Test() (and the rest of your Test class methods) from Test.cpp. This almost always happens when you forget to include the source file with your class implementations in your build command.

How to Fix It

Option 1: Compile all files in one go

If you're using GCC (g++) or Clang, run this terminal command:

g++ main.cpp Test.cpp -o test_program

This tells the compiler to compile both main.cpp and Test.cpp, then link their compiled object files into a single executable named test_program. You can run it afterward with ./test_program.

For larger projects (or if you just prefer splitting the steps), do this:

# Compile Test.cpp to a reusable object file
g++ -c Test.cpp -o Test.o
# Compile main.cpp to another object file
g++ -c main.cpp -o main.o
# Link both object files into an executable
g++ main.o Test.o -o test_program

Bonus: Fix a Hidden Compilation Issue

Wait, I spotted one small mistake in your code that will throw another error once you fix the linker problem: your set function's declaration and implementation don't match.

In Test.hpp, you declared:

void set(int a);

But in Test.cpp, you implemented it to return an int:

int Test::set(int a){
    this->myVal=a;
}

Update the implementation to match the declaration (return void):

void Test::set(int a){
    this->myVal=a;
}

Otherwise, you'll get a compiler error about conflicting return types.

Once you make these changes, your code should compile and run smoothly, outputting:

15
69

内容的提问来源于stack exchange,提问作者Sidwirb

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 18:19:09