- Forum
- Other
- General Programming
- Qt c++ open && ioctl
Thread: Qt c++ open && ioctl
-
24th August 2015, 19:47
#1
Hi i need some help
if((fd = open("/dev/sda",O_RDONLY)) < 0)
To copy to clipboard, switch view to plain text mode
if((err = ioctl(fd,HDIO_GET_IDENTITY,&hd)) < 0)
To copy to clipboard, switch view to plain text mode
headers
#include <linux/types.h>
#include <linux/hdreg.h>
#include <linux/fcntl.h>
To copy to clipboard, switch view to plain text mode
error: 'open' was not declared in this scope
To copy to clipboard, switch view to plain text mode
error: 'ioctl' was not declared in this scope
To copy to clipboard, switch view to plain text mode
What’s the problem ?
Added after 1 33 minutes:
up up up up up up
Last edited by BuranereLoo; 24th August 2015 at 19:47.
-
24th August 2015, 20:25
#2
Re: Qt c++ open && ioctl
Hello,
try the following includes:
#include <sys/types.h>
#include <linux/hdreg.h>
#include <sys/ioctl.h>
#include <fcntl.h>
To copy to clipboard, switch view to plain text mode
Regards
ars
-
The following user says thank you to ars for this useful post:
BuranereLoo (24th August 2015)
-
24th August 2015, 20:42
#3
-
24th August 2015, 22:43
#4
Re: Qt c++ open && ioctl
The required headers for system calls are documented in Section 2 of the manual pages
$ man 2 open
$ man 2 ioctl
To copy to clipboard, switch view to plain text mode
You might also learn patience, especially since you are asking a generic C programming question in a Qt-specific forum.
Similar Threads
-
Replies: 2
Last Post: 25th September 2014, 08:50
-
Replies: 0
Last Post: 20th March 2013, 06:31
-
Replies: 3
Last Post: 15th November 2010, 08:55
-
Replies: 3
Last Post: 25th August 2010, 13:39
-
Replies: 7
Last Post: 27th August 2009, 19:52
Bookmarks
Bookmarks
![](data:image/svg+xml,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%20viewBox='0%200%200%200'%3E%3C/svg%3E)
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
- BB code is On
- Smilies are On
- [IMG] code is On
- [VIDEO] code is On
- HTML code is Off
Forum Rules
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.
I have get gcc8.2 on aliyun Centos7, but when I get gdb-8.2 and use
./configure
make
then it occur compile error in ser-tcp.c. Here are error infos:
ser-tcp.c:64:13: error: conflicting declaration ‘typedef int socklen_t’
typedef int socklen_t;
^~~~~~~~~
In file included from build-gnulib/import/unistd.h:40,
from ./gnulib/import/pathmax.h:42,
from ./common/common-defs.h:84,
from defs.h:28,
from ser-tcp.c:20:
/usr/include/unistd.h:274:21: note: previous declaration as ‘typedef __socklen_t socklen_t’
typedef __socklen_t socklen_t;
^~~~~~~~~
ser-tcp.c: In function ‘int net_open(serial*, const char*)’:
ser-tcp.c:223:19: error: ‘FIONBIO’ was not declared in this scope
ioctl (scb->fd, FIONBIO, &ioarg);
^~~~~~~
ser-tcp.c:223:3: error: ‘ioctl’ was not declared in this scope
ioctl (scb->fd, FIONBIO, &ioarg);
^~~~~
As for gcc-compiler, first I install a gcc-4.8.5 by default from yum.Then download gcc-8.2 and compile and replace.
Here are my gcc-8.2 -v infos:
Using built-in specs.
COLLECT_GCC=gcc
COLLECT_LTO_WRAPPER=/usr/local/libexec/gcc/x86_64-pc-linux-gnu/8.2.0/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: ../gcc-8.2.0/configure --enable-checking=release --enable- languages=c,c++ --disable-multilib
Thread model: posix
gcc version 8.2.0 (GCC)
By the way, it’s not because of not including header, needed header was divided by Macro in the code.The question is why the macro not right in compiling.
This topic has been deleted. Only users with topic management privileges can see it.
Find the code below. What i am doing wrong. The similar code works in plain GCC compliling. Brings the error close() was not declared in this scope. The same for write() . open() is Ok.
@#ifndef KSEG_DH
#define KSEG_DH
#include «QtGlobal»
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/param.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include </usr/include/sys/io.h>
#include <sys/stat.h>
#include <sys/errno.h>
#include </usr/include/sys/fcntl.h>
#include </usr/include/linux/mtio.h>
…..
#include «KSEG_D.h»
…..
int KSEG_D::CloseOutTape()
{
close( idOutTape );
return 0;
}@
Do you mind to enlighten us and tell us the tool chain where the compile fails?
Exactly.
@#include </usr/include/sys/io.h>@
is not a good idea:-) The compiler checks all the include pathes for the files you give and /usr/include is in the list of include pathes on any decent unix-based system. sys/types.h is already found and most likely located right next to sys/io.h.
Are you planing on asking here about each and every method you need to include somewhere? You were the guy that asked about ioctl before, aren’t you? Please check the documentation of the methods you use for the include files needed (or check /usr/include manually, or read a book, or check the working non-Qt code you have).
Thank you. You are so kind. I never asked if i am not sure that i tryed everything i can find out. Some people not so smart and need help
Ok, sorry if I was patronizing, but your question led me to believe that you did none of the following:
check the documentation, e.g. by doing «man 2 close» to get the man page (assuming you are on a unix-oid OS, going by you including /usr/include)?
check a book on C programming. close/open/write/read are pretty well described in any of them. C++ books on the other hand tend to not cover them to extensively since C++ provides more high level directives for file handling. Qt has some even more high level classes for that, too.
google for «close function in linux»? That gets you the man page as the first hit.
run «grep write /usr/include»? That will get you lots of hits, so that is most likely not the preferred way to go;-)
Thank you. I was out of the office, so can not reply promptly. The problem solved. Brief description:
- I could not find ioctl.h. It was really stupid error – I was testing the application on Widows platform that is not proper for ioctl
- The error aroused during compilation as close() ( read(), write() ) is not defined. In Linux to use this in *.cpp mtio.h needs to be included.
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <sys/socket.h>
#include <sys/unistd.h>
#include <sys/types.h>
#include <sys/errno.h>
#include <netinet/in.h>
#include <signal.h>
#include <iostream>
#include <thread>
using namespace std;
#define BUFFSIZE 2048
#define DEFAULT_PORT 4001 //
#define MAXLINK 2048
void connecter()
{
printf("Listening...n");
while (true)
{
signal(SIGINT, stopServerRunning); //
//
connfd = accept(sockfd, NULL, NULL);
if (-1 == connfd)
{
printf("Accept error(%d): %sn", errno, strerror(errno));
return -1;
}
}
}
void listener()
{
while(true)
{
bzero(buff, BUFFSIZE);
//
recv(connfd, buff, BUFFSIZE - 1, 0);
//
printf("клиент: %sn", buff);
//
send(connfd, buff, strlen(buff), 0);
}
}
void sender()
{
while(true)
{
printf("Please input: ");
scanf("%s", buff);
send(connfd, buff, strlen(buff), 0);
bzero(buff, sizeof(buff));
recv(connfd, buff, BUFFSIZE - 1, 0);
printf("recv: %sn", buff);
}
}
int sockfd, connfd;
void stopServerRunning(int p)
{
close(sockfd);
printf("Close Servern");
exit(0);
}
int main()
{
struct sockaddr_in servaddr;
char buff[BUFFSIZE];
//
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (-1 == sockfd)
{
printf("Create socket error(%d): %sn", errno, strerror(errno));
return -1;
}
//
//
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port = htons(DEFAULT_PORT);
if (-1 == bind(sockfd, (struct sockaddr*)&servaddr, sizeof(servaddr)))
{
printf("Bind error(%d): %sn", errno, strerror(errno));
return -1;
}
//
//
if (-1 == listen(sockfd, MAXLINK))
{
printf("Listen error(%d): %sn", errno, strerror(errno));
return -1;
}
while(true)
{
thread my_thread(connecter);
if(connfd == true)
break;
}
thread my_thread(connecter);
thread my_thread(listener);
thread my_thread(sender);
return 0;
}
}
это исходный код программы, хотел написать что-то вроде чата на сокетах. Я попытался скомпилировать код, но он мне выдал несколько ошибок «was not declared in this scope». Вот вывод компилятора:
server.cpp: In function ‘void connecter()’:
server.cpp:24:24: error: ‘stopServerRunning’ was not declared in this scope
24 | signal(SIGINT, stopServerRunning); // Это предложение используется для выключения сервера при вводе Ctrl + C
|
server.cpp:26:9: error: ‘connfd’ was not declared in this scope
26 | connfd = accept(sockfd, NULL, NULL);
| ^~~~~~
server.cpp:26:25: error: ‘sockfd’ was not declared in this scope; did you mean ‘socket’?
26 | connfd = accept(sockfd, NULL, NULL);
| ^~~~~~
| socket
server.cpp: In function ‘void listener()’:
server.cpp:39:15: error: ‘buff’ was not declared in this scope
39 | bzero(buff, BUFFSIZE);
| ^~~~
server.cpp:41:14: error: ‘connfd’ was not declared in this scope
41 | recv(connfd, buff, BUFFSIZE - 1, 0);
| ^~~~~~
server.cpp: In function ‘void sender()’:
server.cpp:54:21: error: ‘buff’ was not declared in this scope
54 | scanf("%s", buff);
| ^~~~
server.cpp:55:14: error: ‘connfd’ was not declared in this scope
55 | send(connfd, buff, strlen(buff), 0);
| ^~~~~~
я думаю, что все эти ошибки идут из одной проблемы, но не могу понять откуда
SergeyKagen 3 / 4 / 2 Регистрация: 02.04.2018 Сообщений: 315 |
||||
1 |
||||
19.04.2019, 22:16. Показов 131712. Ответов 14 Метки нет (Все метки)
Простой код, но Arduino IDE напрочь отказывается принимать переменные. Что за глюк или я что-то неправильно делаю?
ошибка при компиляции «‘count’ was not declared in this scope», что не так?
__________________
0 |
marat_miaki 495 / 389 / 186 Регистрация: 08.04.2013 Сообщений: 1,688 |
||||
19.04.2019, 23:26 |
2 |
|||
Решение
1 |
Lavad 0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
||||||||
14.09.2019, 22:33 |
3 |
|||||||
Доброго времени суток!
В loop() делаю вызов:
При компиляции выделяется этот вызов, с сообщением: ‘myDisplay’ was not declared in this scope Замучился искать инфу о декларации/обьявлении функции. Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции P.S. Код, что использовал в качестве функции, работоспособен. Раньше находился в loop(). Скетч постепенно разрастается, много однотипных обращений к дисплею…
0 |
8385 / 6147 / 615 Регистрация: 10.12.2010 Сообщений: 28,683 Записей в блоге: 30 |
|
14.09.2019, 23:57 |
4 |
Создал функцию (за пределами setup и loop), Перевидите на нормальный язык. В другом файле что ли? Добавлено через 1 минуту
Замучился искать инфу о декларации/обьявлении функции. Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции Читать учебники по С++ не пробовали? https://metanit.com/cpp/tutorial/3.1.php Специфика Arduino лишь отличается тем что пред объявления не всегда нужны. Добавлено через 7 минут
0 |
ValeryS Модератор 8759 / 6549 / 887 Регистрация: 14.02.2011 Сообщений: 22,972 |
||||
15.09.2019, 00:09 |
5 |
|||
Везде, что находил, понимал одно: если ты вызываешь функцию, это и есть обьявление функции это где ж такое написано?
а объявить уже в удобном месте
0 |
0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
|
15.09.2019, 00:48 |
6 |
Неделю назад ВПЕРВЫЕ включил Arduino Uno. Написал на том же языке, что и читал на всяких форумах и справочниках по Arduino :-). За пределами этих функций — значит не внутри них. Обе приведенных Вами ссылок просмотрел, проверил в скетче… В итоге вылезла другая ошибка: void myDisplay(byte x, byte y, char str) тоже пробовал. Та же ошибка. Что не так на этот раз?
0 |
Модератор 8759 / 6549 / 887 Регистрация: 14.02.2011 Сообщений: 22,972 |
|
15.09.2019, 01:26 |
7 |
В итоге вылезла другая ошибка: точку с запятой в конце поставил?
1 |
Lavad 0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
||||||||||||
15.09.2019, 08:46 |
8 |
|||||||||||
Вот скетч. Проще некуда.
Любое из трех так называемых «объявлений» (строки 7…9) выдает одну и ту же ошибку — я пытаюсь объявить функцию как переменную. Добавлено через 9 минут
Компилятор задумался (я успел обрадоваться), но, зараза :-), он снова поставил свой автограф undefined reference to `myDisplay(unsigned char, unsigned char, char, float) На этот раз он пожаловался на строку вызова функции. Добавлено через 34 минуты
Dispay вместо Display Добавлено через 8 минут
0 |
ValeryS Модератор 8759 / 6549 / 887 Регистрация: 14.02.2011 Сообщений: 22,972 |
||||||||
15.09.2019, 10:36 |
9 |
|||||||
void myDisplay(byte, byte, char, float) = 0; вот так не надо делать(приравнивать функцию к нулю) Добавлено через 5 минут
void myDispay(byte x, byte y, char str, float temp)
myDisplay(0, 0, «C», temp); просишь чтобы функция принимала символ
или проси передавать строку, например так
1 |
Avazart 8385 / 6147 / 615 Регистрация: 10.12.2010 Сообщений: 28,683 Записей в блоге: 30 |
||||
15.09.2019, 12:02 |
10 |
|||
Кроме того наверное лучше так:
Тогда можно будет вынести ф-цию в отдельный файл/модуль.
1 |
locm |
15.09.2019, 21:07
|
Не по теме:
Arduino Uno.
AVR (Basic, немного Assembler). Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере.
0 |
Avazart |
15.09.2019, 21:21
|
Не по теме:
Arduino Uno это AVR, для которого можете писать на бейсике или ассемблере. Но лучше не надо …
0 |
Lavad 0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
||||
16.09.2019, 12:12 |
13 |
|||
это где ж такое написано? Оказалось, что я верно понял чтиво по справочникам:
вот так не надо делать(приравнивать функцию к нулю)… Методом проб и ошибок уже понял :-).
или передавай символ… Если передаю в одинарных кавычках более одного символа, а функция ждет как
или проси передавать строку, например так… Буквально вчера попалось это в справочнике, но как-то не дошло, что тоже мой вариант :-).
Кроме того наверное лучше так:
Тогда можно будет вынести ф-цию в отдельный файл/модуль. Благодарю за совет! Как-нибудь проверю…
0 |
8385 / 6147 / 615 Регистрация: 10.12.2010 Сообщений: 28,683 Записей в блоге: 30 |
|
16.09.2019, 12:54 |
14 |
Оказалось, что я верно понял чтиво по справочникам: если ты вызываешь функцию, это и есть обьявление функции Нафиг выкиньте эти справочники.
0 |
0 / 0 / 0 Регистрация: 03.10.2015 Сообщений: 25 |
|
16.09.2019, 13:00 |
15 |
Ссылки Ваши добавлены в закладки. Время от времени заглядываю.
0 |
Example
This error happens if a unknown object is used.
Variables
Not compiling:
#include <iostream>
int main(int argc, char *argv[])
{
{
int i = 2;
}
std::cout << i << std::endl; // i is not in the scope of the main function
return 0;
}
Fix:
#include <iostream>
int main(int argc, char *argv[])
{
{
int i = 2;
std::cout << i << std::endl;
}
return 0;
}
Functions
Most of the time this error occurs if the needed header is not
included (e.g. usingstd::cout
without#include <iostream>
)
Not compiling:
#include <iostream>
int main(int argc, char *argv[])
{
doCompile();
return 0;
}
void doCompile()
{
std::cout << "No!" << std::endl;
}
Fix:
#include <iostream>
void doCompile(); // forward declare the function
int main(int argc, char *argv[])
{
doCompile();
return 0;
}
void doCompile()
{
std::cout << "No!" << std::endl;
}
Or:
#include <iostream>
void doCompile() // define the function before using it
{
std::cout << "No!" << std::endl;
}
int main(int argc, char *argv[])
{
doCompile();
return 0;
}
Note: The compiler interprets the code from top to bottom (simplification). Everything must be at least declared (or defined) before usage.
Tips: If you need C++ homework help from experts, you can always rely upon assignment helpers.