错误:未定义对"审查()"的引用

Error: undefined reference to `censorship()'

本文关键字:引用 审查 未定义 错误      更新时间:2023-10-16

可能重复:
什么是未定义的引用/未解决的外部符号错误,如何修复?

我有main.cpp:

#include "censorship_dec.h"
using namespace std;
int main () {
    censorship();
    return 0;
}

这是我的censorship_dec.h:

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
void censorship();

这是我的censorship_mng.cpp:

#include "censorship_dec.h"
using namespace std;
void censorship()
{
   cout << "bla bla bla" << endl;
}

我试着在SSH(Linux(中运行这些文件,所以我写了:make main,但我得到了:

g++     main.cpp   -o main
/tmp/ccULJJMO.o: In function `main':
main.cpp:(.text+0x71): undefined reference to `censorship()'
collect2: ld returned 1 exit status
make: *** [main] Error 1

请帮忙!

您必须指定定义censorship的文件。

g++ main.cpp censorship_mng.cpp -o main

您必须在编译命令中添加censorship_mng.cpp

g++main.cpp审查_mng.cpp-o主


另一个解决方案(如果您真的不想更改编译命令(是将void censorship();转换为inline函数,并将其从.cpp移动到.h

censorship_dec.h:

#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
inline void censorship()
{
  // your code
}

并从censorship_mng.cpp文件中删除void censorship()

一旦项目开始使用几个源文件编译成一个二进制文件,手动编译就会变得乏味。

这通常是您开始使用构建系统的时候,例如Makefile

使用默认构建规则的非常简单的Makefile可能看起来像

default: main
# these flags are here only for illustration purposes
CPPFLAGS=-I/usr/include
CFLAGS=-g -O3
CXXFLAGS=-g -O3
LDFLAGS=-lm
# objects (.o files) will be compiled automatically from matching .c and .cpp files
OBJECTS=bar.o bla.o foo.o main.o
# application "main" build-depends on all the objects (and linksthem together)
main: $(OBJECTS)