[英]Makefile for linking an extern global
I'm trying to use the g_struct
variable that's defined in struct.cpp
and declared in struct.hpp
inside the test.cpp
, but the linking fails.我正在尝试使用在g_struct
中定义并在struct.hpp
中的struct.cpp
声明的struct.hpp
test.cpp
,但链接失败。 Why is that?这是为什么?
// test.cpp
#include "struct.hpp"
int main(void)
{
g_struct.a = 1;
return 0;
}
// struct.cpp
#include "struct.hpp"
Struct g_struct;
// struct.hpp
#pragma once
struct Struct {
int a;
};
extern Struct g_struct;
# Makefile
CC = g++
all: struct.o test
test: test.cpp
$(CC) -o test test.cpp
struct.o: struct.cpp
$(CC) -c -o struct.o struct.cpp
.PHONY: clean
clean:
rm -f *.o test
Linking error:链接错误:
$ make
g++ -c -o struct.o struct.cpp
g++ -o test test.cpp
/tmp/ccgSoJhd.o: In function `main':
test.cpp:(.text+0xd): undefined reference to `g_struct'
collect2: error: ld returned 1 exit status
Makefile:6: recipe for target 'test' failed
make: *** [test] Error 1
If I link without the -c
flag, I get:如果我在没有-c
标志的情况下进行链接,我会得到:
$ make
g++ -o struct.o struct.cpp
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
collect2: error: ld returned 1 exit status
Makefile:9: recipe for target 'struct.o' failed
make: *** [struct.o] Error 1
You have to link struct.o
, which has Struct g_struct;
你必须链接struct.o
,它有Struct g_struct;
. .
test: test.cpp
$(CC) -o test test.cpp struct.o
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.