Ошибка в avr undefined reference to

My main.c is as below

#include <avr/io.h>
#include<avr/interrupt.h>
#include<util/delay.h>
#include <string.h>
#include "main.h"
#include "globle.h"
#include "LCD.h"

int  main()

{

...
...
...

lcdInit(0xc0);
lcdScreen(0);
.
.
.


return 0; 

}

The definition of lcdInit(0xc0); and lcdScreen(0); is in my lcd.c file
and I have a header file lcd.h having the following lines:

void lcdInit(char);
void lcdScreen(char);

But still I am getting:

C:Documents and SettingsTanvMy Documentsmy_project5default/../Main.c:95: >undefined >reference to
`lcdInit’

and

C:Documents and SettingsTanvrMy
Documentsmy_project5default/../Main.c:96: undefined reference to
`lcdScreen’

What is wrong here?

asked Aug 30, 2013 at 13:12

user2733045's user avatar

This is a linker error.

You are not building your program properly, you need to compile all C files together, like so:

$ gcc-avr -o program main.c lcd.c

or link them together from object files if you compile separately.

answered Aug 30, 2013 at 13:16

unwind's user avatar

unwindunwind

390k64 gold badges468 silver badges605 bronze badges

2

enter image description here

Add source and header files to your project by
1. Right click «Source Files» then «Add Existing Source File(s)»
2. Right click «Header Files» then «Add Existing Header File(s)»

Refer to Add Source to Project Step 6.

answered Dec 15, 2014 at 11:53

Macit's user avatar

MacitMacit

2763 silver badges9 bronze badges

0

I had the same problem and I added the files to the project from the beginning and they were compiled together. But this did not solve the problem and I accidentally noticed that I made a mistake, namely the file of the implementation of the functions of the library had the extension .c, and the main extension .cpp. To solve the problem, I simply reassembled the project in c format.

Emma's user avatar

Emma

27.3k11 gold badges43 silver badges69 bronze badges

answered Nov 12, 2020 at 22:01

Віктор Пяста's user avatar

PiTik

1

02.01.2012, 18:19. Показов 9792. Ответов 11


Студворк — интернет-сервис помощи студентам

Привет всем! Господа не могу найти ошибку: после компиляции выскакивает вот такая ошибка main.c:undefined reference to имя функции.
Ситуация такая: есть главный файл main.c и заголовочный uart.h,который я подключаю как #include «uart.h»,функция,имя которой высвечивается в ошибке определена в этом заголовочном файле. В чем может быть проблема? :)

0 / 0 / 0

Регистрация: 12.04.2010

Сообщений: 3,260

02.01.2012, 18:23

2

файл h должен быть в папке с проектом



0



0 / 0 / 0

Регистрация: 18.03.2010

Сообщений: 1,112

02.01.2012, 18:24

3

А в проект этот заголовочный файл добавлен?



0



PiTik

02.01.2012, 18:46

4

файл h должен быть в папке с проектом

Файлы все находятся в одной папке

А в проект этот заголовочный файл добавлен?

Не представляю, как их добавить? Я просто написал заголовочный файл uart.h и с помощью #nclude «uart.h» подключил,а в настройках WinAvr ничего не трогал или надо было? Просветите пожалуйста.

0 / 0 / 0

Регистрация: 23.01.2010

Сообщений: 1,142

02.01.2012, 18:52

5

А те функции, на которые ваш uart.h ссылается в каком файле находятся? И включён ли данный файл в проект?



0



PiTik

02.01.2012, 18:57

6

Цитата
Сообщение от THI BIOST

А те функции, на которые ваш uart.h ссылается в каком файле находятся? И включён ли данный файл в проект?

Они все в одной папке находятся,только для меня новое-это «подключить файлы к проекту». Как это сделать в WinAvr? Сам недавно на него сел.
Может в мейкфайле че-нибудь надо дописать? Вот кусок,где указано имя главного файла:

Код

...
# Target file name (wythout extension).
TARGET = main

# Object files directory
#     To put object files in current directory, use a dot (.), do NOT make
#     this an empty or blank macro!
OBJDIR = .

# List C source files here. (C dependencies are outomatically generated.)
SRC = $(TARGET).c

# List C++ source files here. (C dependencies are outomatically generated.)
CPPSRC =
...

0 / 0 / 0

Регистрация: 23.01.2010

Сообщений: 1,142

02.01.2012, 19:01

7

Я не пользуюсь винавром, но, по 20 годам программирования на C — все файлы исходников должны быть включены в проект, дабы откомпилялись компилятором и собрались линкером. То есть либо мышой в проект, либо руками в makefile.



0



0 / 0 / 0

Регистрация: 23.01.2010

Сообщений: 1,142

02.01.2012, 19:05

8

Посмотрел, в 4 студии — кликнуть правой клавишей мыша на Source files и выбрать Add Existing Source File(s)



0



PiTik

02.01.2012, 19:17

9

Цитата
Сообщение от THI BIOST

Посмотрел, в 4 студии — кликнуть правой клавишей мыша на Source files и выбрать Add Existing Source File(s)

Все,спасибо, я разобрался. Надо было дописать в мейкфайле имя сишного файла uart.c для заголовка uart.h,если я правильно понял вот так:

Код

# List C source files here. (C dependencies are outomatically generated.)
SRC = $(TARGET).c uart.c

Подправьте меня,если что не так.вроде бы скомпилился :)

0 / 0 / 0

Регистрация: 14.02.2010

Сообщений: 494

02.01.2012, 21:16

10

Все так, H-файл подключать к проекту не надо, он и так прекрасно разворачивается с помощью #include. А вот исходники (*.c, *.cpp итд) подключать надо, если IDE — то где-то в свойствах проекта, если Makefile — то все примерно так, как вы сделали.



0



0 / 0 / 1

Регистрация: 27.01.2010

Сообщений: 3,435

02.01.2012, 23:14

11

Замечу отвечавшим: вы правы и неправы.
Любые файлы, которые включены в другие посредством #include включать в проект совсем не обязательно.

Файлы же, включенные в проект, компилируются и линкуются отдельно, с проверкой на изменения. Это позволяет уменьшить время на компиляцию и линковку больших проектов, где делаются изменения только в некоторых файлах.

Если же делать через #include — то препроцессор все равно включит тектс этих файлов в основной, со всеми вытекающими — компиляция и линковка.

Если же случается «пересортица» — файлы находятся и в проекте, и в «инклудах» — в некоторых случаях ничего плохого не происходит (за исключением времени на компиляцию), а в других случаях возможны ошибки на этапе компиляции и линковки.



0



0 / 0 / 0

Регистрация: 14.02.2010

Сообщений: 494

04.01.2012, 21:00

12

Заголовок не компилируется без специальных свистоплясок, которые рядовому пользователю даже в голову не приходят. Равно как и подключать *.c с помощью директивы #include (хотя до этого извращения можно дойти своим мозгом). Так, что если компилятор ругается, то в 99% не подключен нужный заголовой, если линковщик ругается — файл с нужным кодом не подключен к проекту (и не компилировался соответственно)

Большинство таких проблем из-за непонимания, как работает препроцессор-компилятор-линковщик, всем кто пишет на c/cpp и не знает этих простых вещей очень рекомендую быстренько самообразовываться, в дальнейшем это очень пригодится



0



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

04.01.2012, 21:00

12

Offline

Зарегистрирован: 01.11.2015

День добрый, помогите с ошибкой компиляции.

Проект в Atmel studio 7, среда ардуино 1.6.12.

Не пойму в чем проблема, при сборке проекта среда выдает следующие ошибки:

Severity	Code	Description	Project	File	Line
Error		undefined reference to `IRrecv::decode(decode_results*)'	project	D:ardu_projectsLAMP_V3LAMP_V3projectSketch.cpp	36
Error		ld returned 1 exit status	project	collect2.exe	0
Error		recipe for target 'project.elf' failed	project	D:ardu_projectsLAMP_V3LAMP_V3projectDebugMakefile	130
Error		undefined reference to `IRrecv::decode(decode_results*)'	project	D:ardu_projectsLAMP_V3LAMP_V3projectSketch.cpp	33
Error		undefined reference to `IRrecv::enableIRIn()'	project	D:ardu_projectsLAMP_V3LAMP_V3projectSketch.cpp	26
Error		undefined reference to `IRrecv::IRrecv(int)'	project	D:ardu_projectsLAMP_V3LAMP_V3projectSketch.cpp	16
Error		undefined reference to `IRrecv::resume()'	project	D:ardu_projectsLAMP_V3LAMP_V3projectSketch.cpp	38

Проект прилагаю

The code looks fine — you’re just having trouble with the compiling/linking.

If you want to do the compilation by hand, the easiest way to go is to make sure that all the files you need (.h and .c) are all in the same directory. This works great for small personal projects.

Then you can compile simply with avr-gcc -Os -Wall -DF_CPU=16000000UL -DBAUD=9600UL -mmcu=atmega328p *.c -o serial.o

where if you want to be explicit, you can list out all the something.c files in place of the *.c

Because I reuse the serial libraries all over the place, I kept them in one place and linked to them. That ends up being all sorts of hassle — you need to use the -I flag to tell the compiler where the .h files are located, and you need to specify a full path to the corresponding source files.

That, plus the other compilation options that are nice to use on the AVR platform, lead me to write up a makefile and use make for the book. It’s a bit opaque for the beginner, which I don’t like, but it should work more easily.

If I were re-doing it, I would consider simply copying the pinDefines.h and the USART.c and .h files into every directory that uses them. (You can do that yourself.) It’s a horrible duplication of code, that makes any changes difficult to manage, but it’s more straightforward.

Arduino Forum

Loading

Понравилась статья? Поделить с друзьями:
  • Ошибка в assassins creed 2 код ошибки 2
  • Ошибка в armored warfare ошибка авторизации
  • Ошибка в arma 3 bad version
  • Ошибка в arma 3 0x0000dead
  • Ошибка в api запросе код 100