how to compile these code(simple share library)

h3w4 2007-01-12 02:23:19
/////////////sharelib.h
#ifndef _SHARE_LIB_
#define _SHARE_LIB_
void fun();
#endif

/////////////sharelib.cpp
#include "sharelib.h"
#include <iostream>

void fun()
{
std::cout << "int fun" << std::endl;
}

//////////////////////////////
/////////////////main.cpp
extern void (*fun)();
int main()
{
fun();
return 0;
}

//////////////////////////compile code
#g++ -c -fPIC sharelib.cpp -o libshare.0 // pass

#ld -shared -soname sharelib.1 libshare.0 -o libshare.so // pass

#ls -l
-rw-r--r-- 1 root root 2584 Jan 12 14:24 libshare.0
-rwxr-xr-x 1 root root 3794 Jan 12 14:24 libshare.so
-rw-r--r-- 1 hh users 63 Jan 12 13:55 main.cpp
-rw-r--r-- 1 root root 213 Jan 12 14:01 makefile
-rw-r--r-- 1 root root 121 Jan 12 14:05 sharelib.cpp
-rw-r--r-- 1 root root 63 Jan 12 14:05 sharelib.h

#g++ -o sharetest main.cpp -L./ -lshare // error

//////////////////////////error message:
/tmp/ccy9frxb.o: In function `main':
main.cpp:(.text+0x12): undefined reference to `fun'
/usr/lib/gcc/i586-suse-linux/4.1.0/../../../../i586-suse-linux/bin/ld: sharetest: hidden symbol `__dso_handle' in /usr/lib/gcc/i586-suse-linux/4.1.0/crtbegin.o is referenced by DSO
/usr/lib/gcc/i586-suse-linux/4.1.0/../../../../i586-suse-linux/bin/ld: final link failed: Nonrepresentable section on output
collect2: ld returned 1 exit status











...全文
353 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zhousqy 2007-01-12
  • 打赏
  • 举报
回复
debian:~/learn# export LD_LIBRARY_PATH=.
debian:~/learn# ./a.out
int fun
debian:~/learn#
h3w4 2007-01-12
  • 打赏
  • 举报
回复
to zhousqy(标准C匪徒)(甩拉,甩拉)

i do so
#g++ -fPIC -shared -o libshare.so sharelib.cpp
#g++ main.cpp -L. -lshare -o tst

but when i run it, it occurs again

tst: error while loading shared libraries: libshare.so: cannot open shared object file: No such file or directory
zhousqy 2007-01-12
  • 打赏
  • 举报
回复
$g++ -fPIC -shared -o libshare.so sharelib.cpp
$g++ main.cpp -L. -lshare
h3w4 2007-01-12
  • 打赏
  • 举报
回复
thanks first
i modify the main.cpp

#include "sharelib.h"
int main()
{
fun();
return 0;
}

and compile
#g++ -o sharetest main.cpp -L./ -lshare

////////////////////////////////////error message
/usr/lib/gcc/i586-suse-linux/4.1.0/../../../../i586-suse-linux/bin/ld: sharetest: hidden symbol `__dso_handle' in /usr/lib/gcc/i586-suse-linux/4.1.0/crtbegin.o is referenced by DSO
/usr/lib/gcc/i586-suse-linux/4.1.0/../../../../i586-suse-linux/bin/ld: final link failed: Nonrepresentable section on output
collect2: ld returned 1 exit status

there still have promble, where i did wrong???
a_b_c_abc6 2007-01-12
  • 打赏
  • 举报
回复
//extern void (*fun)();这是声明一个函数指针
extern void fun();//修改为这样
int main()
{
fun();
return 0;
}
Fundamentals of the JavaMail API Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Table of Contents If you're viewing this document online, you can click any of the topics below to link directly to that section. 1. Tutorial tips 2 2. Introducing the JavaMail API 3 3. Reviewing related protocols 4 4. Installing JavaMail 6 5. Reviewing the core classes 8 6. Using the JavaMail API 13 7. Searching with SearchTerm 21 8. Exercises 22 9. Wrapup 32 Fundamentals of the JavaMail API Page 1 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 1. Tutorial tips Should I take this tutorial? Looking to incorporate mail facilities into your platform-independent Java solutions? Look no further than the JavaMail API, which offers a protocol-independent model for working with IMAP, POP, SMTP, MIME, and all those other Internet-related messaging protocols. With the help of the JavaBeans Activation Framework (JAF), your applications can now be mail-enabled through the JavaMail API. Concepts After completing this module you will understand the: * Basics of the Internet mail protocols SMTP, POP3, IMAP, and MIME * Architecture of the JavaMail framework * Connections between the JavaMail API and the JavaBeans Activation Framework Objectives By the end of this module you will be able to: * Send and read mail using the JavaMail API * Deal with sending and receiving attachments * Work with HTML messages * Use search terms to search for messages Prerequisites Instructions on how to download and install the JavaMail API are contained in the course. In addition, you will need a development environment such as the JDK 1.1.6+ or the Java 2 Platform, Standard Edition (J2SE) 1.2.x or 1.3.x. A general familiarity with object-oriented programming concepts and the Java programming language is necessary. The Java language essentials tutorial can help. copyright 1996-2000 Magelang Institute dba jGuru Contact jGuru has been dedicated to promoting the growth of the Java technology community through evangelism, education, and software since 1995. You can find out more about their activities, including their huge collection of FAQs at jGuru.com . To send feedback to jGuru about this course, send mail to producer@jguru.com . Course author: Formerly with jGuru.com , John Zukowski does strategic Java consulting for JZ Ventures, Inc. His latest book is titled Java Collections from Apress . Fundamentals of the JavaMail API Page 2 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 2. Introducing the JavaMail API What is the JavaMail API? The JavaMail API is an optional package (standard extension) for reading, composing, and sending electronic messages. You use the package to create Mail User Agent (MUA) type programs, similar to Eudora, pine, and Microsoft Outlook. The API's main purpose is not for transporting, delivering, and forwarding messages; this is the purview of applications such as sendmail and other Mail Transfer Agent (MTA) type programs. MUA-type programs let users read and write e-mail, whereas MUAs rely on MTAs to handle the actual delivery. The JavaMail API is designed to provide protocol-independent access for sending and receiving messages by dividing the API into two parts: * The first part of the API is the focus of this course --basically, how to send and receive messages independent of the provider/protocol. * The second part speaks the protocol-specific languages, like SMTP, POP, IMAP, and NNTP. With the JavaMail API, in order to communicate with a server, you need a provider for a protocol. The creation of protocol-specific providers is not covered in this course because Sun provides a sufficient set for free. Fundamentals of the JavaMail API Page 3 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 3. Reviewing related protocols Introduction Before looking into the JavaMail API specifics, let's step back and take a look at the protocols used with the API. There are basically four that you'll come to know and love: * SMTP * POP * IMAP * MIME You will also run across NNTP and some others. Understanding the basics of all the protocols will help you understand how to use the JavaMail API. While the API is designed to be protocol agnostic, you can't overcome the limitations of the underlying protocols. If a capability isn't supported by a chosen protocol, the JavaMail API doesn't magically add the capability on top of it. (As you'll soon see, this can be a problem when working with POP.) SMTP The Simple Mail Transfer Protocol (SMTP) is defined by RFC 821 . It defines the mechanism for delivery of e-mail. In the context of the JavaMail API, your JavaMail-based program will communicate with your company or Internet Service Provider's (ISP's) SMTP server. That SMTP server will relay the message on to the SMTP server of the recipient(s) to eventually be acquired by the user(s) through POP or IMAP. This does not require your SMTP server to be an open relay, as authentication is supported, but it is your responsibility to ensure the SMTP server is configured properly. There is nothing in the JavaMail API for tasks like configuring a server to relay messages or to add and remove e-mail accounts. POP POP stands for Post Office Protocol. Currently in version 3, also known as POP3, RFC 1939 defines this protocol. POP is the mechanism most people on the Internet use to get their mail. It defines support for a single mailbox for each user. That is all it does, and that is also the source of a lot of confusion. Much of what people are familiar with when using POP, like the ability to see how many new mail messages they have, are not supported by POP at all. These capabilities are built into programs like Eudora or Microsoft Outlook, which remember things like the last mail received and calculate how many are new for you. So, when using the JavaMail API, if you want this type of information, you have to calculate it yourself. IMAP IMAP is a more advanced protocol for receiving messages. Defined in RFC 2060 , IMAP stands for Internet Message Access Protocol, and is currently in version 4, also known as IMAP4. When using IMAP, your mail server must support the protocol. You can't just change your program to use IMAP instead of POP and expect everything in IMAP to be supported. Assuming your mail server supports IMAP, your JavaMail-based program can take Fundamentals of the JavaMail API Page 4 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks advantage of users having multiple folders on the server and these folders can be shared by multiple users. Due to the more advanced capabilities, you might think IMAP would be used by everyone. It isn't. It places a much heavier burden on the mail server, requiring the server to receive the new messages, deliver them to users when requested, and maintain them in multiple folders for each user. While this does centralize backups, as users' long-term mail folders get larger and larger, everyone suffers when disk space is exhausted. With POP, saved messages get offloaded from the mail server. MIME MIME stands for Multipurpose Internet Mail Extensions. It is not a mail transfer protocol. Instead, it defines the content of what is transferred: the format of the messages, attachments, and so on. There are many different documents that take effect here: RFC 822 , RFC 2045 , RFC 2046 , and RFC 2047 . As a user of the JavaMail API, you usually don't need to worry about these formats. However, these formats do exist and are used by your programs. NNTP and others Because of the split of the JavaMail API between provider and everything else, you can easily add support for additional protocols. Sun maintains a list of third-party providers that take advantage of protocols for which Sun does not provide out-of-the-box support. You'll find support for NNTP (Network News Transport Protocol) [newsgroups], S/MIME (Secure Multipurpose Internet Mail Extensions), and more. Fundamentals of the JavaMail API Page 5 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 4. Installing JavaMail Introduction There are two versions of the JavaMail API commonly used today: 1.2 and 1.1.3. All the examples in this course will work with both. While 1.2 is the latest, 1.1.3 is the version included with the 1.2.1 version of the Java 2 Platform, Enterprise Edition (J2EE), so it is still commonly used. The version of the JavaMail API you want to use affects what you download and install. All will work with JDK 1.1.6+, Java 2 Platform, Standard Edition (J2SE) version 1.2.x, and J2SE version 1.3.x. Note: After installing Sun's JavaMail implementation, you can find many example programs in the demo directory. Installing JavaMail 1.2 To use the JavaMail 1.2 API, download the JavaMail 1.2 implementation, unbundle the javamail-1_2.zip file, and add the mail.jar file to your CLASSPATH. The 1.2 implementation comes with an SMTP, IMAP4, and POP3 provider besides the core classes. After installing JavaMail 1.2, install the JavaBeans Activation Framework. Installing JavaMail 1.1.3 To use the JavaMail 1.1.3 API, download the JavaMail 1.1.3 implementation, unbundle the javamail1_1_3.zip file, and add the mail.jar file to your CLASSPATH. The 1.1.3 implementation comes with an SMTP and IMAP4 provider, besides the core classes. If you want to access a POP server with JavaMail 1.1.3, download and install a POP3 provider. Sun has one available separate from the JavaMail implementation. After downloading and unbundling pop31_1_1.zip, add pop3.jar to your CLASSPATH, too. After installing JavaMail 1.1.3, install the JavaBeans Activation Framework. Installing the JavaBeans Activation Framework All versions of the JavaMail API require the JavaBeans Activation Framework. The framework adds support for typing arbitrary blocks of data and handling it accordingly. This doesn't sound like much, but it is your basic MIME-type support found in many browsers and mail tools today. After downloading the framework, unbundle the jaf1_0_1.zip file, and add the activation.jar file to your CLASSPATH. For JavaMail 1.2 users, you should now have added mail.jar and activation.jar to your CLASSPATH. For JavaMail 1.1.3 users, you should now have added mail.jar, pop3.jar, and activation.jar to your CLASSPATH. If you have no plans of using POP3, you don't Fundamentals of the JavaMail API Page 6 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks need to add pop3.jar to your CLASSPATH. If you don't want to change the CLASSPATH environment variable, copy the jar files to your lib/ext directory under the Java Runtime Environment (JRE) directory. For instance, for the J2SE 1.3 release, the default directory would be C:\jdk1.3\jre\lib\ext on a Windows platform. Using JavaMail with the Java 2 Enterprise Edition If you use J2EE, there is nothing special you have to do to use the basic JavaMail API; it comes with the J2EE classes. Just make sure the j2ee.jar file is in your CLASSPATH and you're all set. For J2EE 1.2.1, the POP3 provider comes separately, so download and follow the steps to include the POP3 provider as shown in the previous section "Installing JavaMail 1.1.3." J2EE 1.3 users get the POP3 provider with J2EE so do not require the separate installation. Neither installation requires you to install the JavaBeans Activation Framework. Exercise Exercise 1. How to set up a JavaMail environment on page 22 Fundamentals of the JavaMail API Page 7 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 5. Reviewing the core classes Introduction Before taking a how-to approach at looking at the JavaMail classes in depth, this section walks you through the core classes that make up the API: Session, Message, Address, Authenticator, Transport, Store, and Folder. All these classes are found in the top-level package for the JavaMail API, javax.mail, though you'll frequently find yourself using subclasses found in the javax.mail.internet package. Session The Session class defines a basic mail session. It is through this session that everything else works. The Session object takes advantage of a java.util.Properties object to get information like mail server, username, password, and other information that can be shared across your entire application. The constructors for the class are private. You can get a single default session that can be shared with the getDefaultInstance() method: Properties props = new Properties(); // fill props with any information Session session = Session.getDefaultInstance(props, null); Or, you can create a unique session with getInstance(): Properties props = new Properties(); // fill props with any information Session session = Session.getDefaultInstance(props, null); In both cases, the null argument is an Authenticator object that is not being used at this time. In most cases, it is sufficient to use the shared session, even if working with mail sessions for multiple user mailboxes. You can add the username and password combination in at a later step in the communication process, keeping everything separate. Message Once you have your Session object, it is time to move on to creating the message to send. This is done with a type of Message . Because Message is an abstract class, you must work with a subclass, in most cases javax.mail.internet.MimeMessage .A MimeMessage is an e-mail message that understands MIME types and headers, as defined in the different RFCs. Message headers are restricted to US-ASCII characters only, though non-ASCII characters can be encoded in certain header fields. To create a Message, pass along the Session object to the MimeMessage constructor: MimeMessage message = new MimeMessage(session); Fundamentals of the JavaMail API Page 8 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Note: There are other constructors, like for creating messages from RFC822-formatted input streams. Once you have your message, you can set its parts, as Message implements the Part interface (with MimeMessage implementing MimePart ). The basic mechanism to set the content is the setContent() method, with arguments for the content and the mime type: message.setContent("Hello", "text/plain"); If, however, you know you are working with a MimeMessage and your message is plain text, you can use its setText() method, which only requires the actual content, defaulting to the MIME type of text/plain: message.setText("Hello"); For plain text messages, the latter form is the preferred mechanism to set the content. For sending other kinds of messages, like HTML messages, use the former. For setting the subject, use the setSubject() method: message.setSubject("First"); Address Once you've created the Session and the Message, as well as filled the message with content, it is time to address your letter with an Address . Like Message, Address is an abstract class. You use the javax.mail.internet.InternetAddress class. To create an address with just the e-mail address, pass the e-mail address to the constructor: Address address = new InternetAddress("president@whitehouse.gov"); If you want a name to appear next to the e-mail address, you can pass that along to the constructor, too: Address address = new InternetAddress("president@whitehouse.gov", "George Bush"); You will need to create address objects for the message's from field as well as the to field. Unless your mail server prevents you, there is nothing stopping you from sending a message that appears to be from anyone. Once you've created the addresses, you connect them to a message in one of two ways. For identifying the sender, you use the setFrom() and setReplyTo() methods. message.setFrom(address) If your message needs to show multiple from addresses, use the addFrom() method: Fundamentals of the JavaMail API Page 9 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Address address[] = ...; message.addFrom(address); For identifying the message recipients, you use the addRecipient() method. This method requires a Message.RecipientType besides the address. message.addRecipient(type, address) The three predefined types of address are: * Message.RecipientType.TO * Message.RecipientType.CC * Message.RecipientType.BCC So, if the message was to go to the vice president, sending a carbon copy to the first lady, the following would be appropriate: Address toAddress = new InternetAddress("vice.president@whitehouse.gov"); Address ccAddress = new InternetAddress("first.lady@whitehouse.gov"); message.addRecipient(Message.RecipientType.TO, toAddress); message.addRecipient(Message.RecipientType.CC, ccAddress); The JavaMail API provides no mechanism to check for the validity of an e-mail address. While you can program in support to scan for valid characters (as defined by RFC 822) or verify the MX (mail exchange) record yourself, these are all beyond the scope of the JavaMail API. Authenticator Like the java.net classes, the JavaMail API can take advantage of an Authenticator to access protected resources via a username and password. For the JavaMail API, that resource is the mail server. The JavaMail Authenticator is found in the javax.mail package and is different from the java.net class of the same name. The two don't share the same Authenticator as the JavaMail API works with Java 1.1, which didn't have the java.net variety. To use the Authenticator, you subclass the abstract class and return a PasswordAuthentication instance from the getPasswordAuthentication() method. You must register the Authenticator with the session when created. Then, your Authenticator will be notified when authentication is necessary. You could pop up a window or read the username and password from a configuration file (though if not encrypted is not secure), returning them to the caller as a PasswordAuthentication object. Properties props = new Properties(); // fill props with any information Authenticator auth = new MyAuthenticator(); Session session = Session.getDefaultInstance(props, auth); Transport The final part of sending a message is to use the Transport class. This class speaks the Fundamentals of the JavaMail API Page 10 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks protocol-specific language for sending the message (usually SMTP). It's an abstract class and works something like Session. You can use the default version of the class by just calling the static send() method: Transport.send(message); Or, you can get a specific instance from the session for your protocol, pass along the username and password (blank if unnecessary), send the message, and close the connection: message.saveChanges(); // implicit with send() Transport transport = session.getTransport("smtp"); transport.connect(host, username, password); transport.sendMessage(message, message.getAllRecipients()); transport.close(); This latter way is best when you need to send multiple messages, as it will keep the connection with the mail server active between messages. The basic send() mechanism makes a separate connection to the server for each method call. Note: To watch the mail commands go by to the mail server, set the debug flag with session.setDebug(true). Store and folder Getting messages starts similarly to sending messages with a Session. However, after getting the session, you connect to a Store , quite possibly with a username and password or Authenticator. Like Transport, you tell the Store what protocol to use: // Store store = session.getStore("imap"); Store store = session.getStore("pop3"); store.connect(host, username, password); After connecting to the Store, you can then get a Folder , which must be opened before you can read messages from it: Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); Message message[] = folder.getMessages(); For POP3, the only folder available is the INBOX. If you are using IMAP, you can have other folders available. Note: Sun's providers are meant to be smart. While Message message[] = folder.getMessages(); might look like a slow operation reading every message from the server, only when you actually need to get a part of the message is the message content retrieved. Once you have a Message to read, you can get its content with getContent() or write its content to a stream with writeTo(). The getContent() method only gets the message content, while writeTo() output includes headers. Fundamentals of the JavaMail API Page 11 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks System.out.println(((MimeMessage)message).getContent()); Once you're done reading mail, close the connection to the folder and store. folder.close(aBoolean); store.close(); The boolean passed to the close() method of folder states whether or not to update the folder by removing deleted messages. Moving on Essentially, understanding how to use these seven classes is all you need for nearly everything with the JavaMail API. Most of the other capabilities of the JavaMail API build off these seven classes to do something a little different or in a particular way, like if the content is an attachment. Certain tasks, like searching, are isolated and are discussed later. Fundamentals of the JavaMail API Page 12 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 6. Using the JavaMail API Introduction You've seen how to work with the core parts of the JavaMail API. In the following sections you'll find a how-to approach for connecting the pieces to do specific tasks. Sending messages Sending an e-mail message involves getting a session, creating and filling a message, and sending it. You can specify your SMTP server by setting the mail.smtp.host property for the Properties object passed when getting the Session: String host = ...; String from = ...; String to = ...; // Get system properties Properties props = System.getProperties(); // Setup mail server props.put("mail.smtp.host", host); // Get session Session session = Session.getDefaultInstance(props, null); // Define message MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Hello JavaMail"); message.setText("Welcome to JavaMail"); // Send message Transport.send(message); You should place the code in a try-catch block, as setting up the message and sending it can throw exceptions. Exercise: Exercise 2. How to send your first message on page 23 Fetching messages For reading mail, you get a session, get and connect to an appropriate store for your mailbox, open the appropriate folder, and get your messages. Also, don't forget to close the connection when done. String host = ...; String username = ...; String password = ...; // Create empty properties Properties props = new Properties(); // Get session Session session = Session.getDefaultInstance(props, null); Fundamentals of the JavaMail API Page 13 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks // Get the store Store store = session.getStore("pop3"); store.connect(host, username, password); // Get folder Folder folder = store.getFolder("INBOX"); folder.open(Folder.READ_ONLY); // Get directory Message message[] = folder.getMessages(); for (int i=0, n=message.length; icode block just displays whom the message is from and the subject. Technically speaking, the list of from addresses could be empty and the getFrom()[0] call could throw an exception. To display the whole message, you can prompt the user after seeing the from and subject fields, and then call the message's writeTo() method if the user wants to see it. BufferedReader reader = new BufferedReader ( new InputStreamReader(System.in)); // Get directory Message message[] = folder.getMessages(); for (int i=0, n=message.length; icom/developerWorks Just because a flag exists doesn't mean the flag is supported by all mail servers or providers. For instance, except for deleting messages, the POP protocol supports none of them. Checking for new mail is not a POP task but a task built into mail clients. To find out what flags are supported, ask the folder with getPermanentFlags(). To delete messages, you set the message's DELETED flag: message.setFlag(Flags.Flag.DELETED, true); Open up the folder in READ_WRITE mode first though: folder.open(Folder.READ_WRITE); Then, when you are done processing all messages, close the folder, passing in a true value to expunge the deleted messages. folder.close(true); There is an expunge() method of Folder that can be used to delete the messages. However, it doesn't work for Sun's POP3 provider. Other providers may or may not implement the capabilities. It will more than likely be implemented for IMAP providers. Because POP only supports single access to the mailbox, you have to close the folder to delete the messages with Sun's provider. To unset a flag, just pass false to the setFlag() method. To see if a flag is set, check it with isSet(). Authenticating yourself You learned that you can use an Authenticator to prompt for username and password when needed, instead of passing them in as strings. Here you'll actually see how to more fully use authentication. Instead of connecting to the Store with the host, username, and password, you configure the Properties to have the host, and tell the Session about your custom Authenticator instance, as shown here: // Setup properties Properties props = System.getProperties(); props.put("mail.pop3.host", host); // Setup authentication, get session Authenticator auth = new PopupAuthenticator(); Session session = Session.getDefaultInstance(props, auth); // Get the store Store store = session.getStore("pop3"); store.connect(); You then subclass Authenticator and return a PasswordAuthentication object from the getPasswordAuthentication() method. The following is one such implementation, with a single field for both. (This isn't a Project Swing tutorial; just enter the two parts in the one field, separated by a comma.) Fundamentals of the JavaMail API Page 15 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks import javax.mail.*; import javax.swing.*; import java.util.*; public class PopupAuthenticator extends Authenticator { public PasswordAuthentication getPasswordAuthentication() { String username, password; String result = JOptionPane.showInputDialog( "Enter 'username,password'"); StringTokenizer st = new StringTokenizer(result, ","); username = st.nextToken(); password = st.nextToken(); return new PasswordAuthentication(username, password); } } Because the PopupAuthenticator relies on Swing, it will start up the event-handling thread for AWT. This basically requires you to add a call to System.exit() in your code to stop the program. Replying to messages The Message class includes a reply() method to configure a new Message with the proper recipient and subject, adding "Re: " if not already there. This does not add any content to the message, only copying the from or reply-to header to the new recipient. The method takes a boolean parameter indicating whether to reply to only the sender (false) or reply to all (true). MimeMessage reply = (MimeMessage)message.reply(false); reply.setFrom(new InternetAddress("president@whitehouse.gov")); reply.setText("Thanks"); Transport.send(reply); To configure the reply-to address when sending a message, use the setReplyTo() method. Exercise: Exercise 4. How to reply to mail on page 27 Forwarding messages Forwarding messages is a little more involved. There is no single method to call, and you build up the message to forward by working with the parts that make up a message. A mail message can be made up of multiple parts. Each part is a BodyPart , or more specifically, a MimeBodyPart when working with MIME messages. The different body parts get combined into a container called Multipart or, again, more specifically a MimeMultipart . To forward a message, you create one part for the text of your message and a second part with the message to forward, and combine the two into a multipart. Then you add the multipart to a properly addressed message and send it. That's essentially it. To copy the content from one message to another, just copy over its Fundamentals of the JavaMail API Page 16 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks DataHandler , a class from the JavaBeans Activation Framework. // Create the message to forward Message forward = new MimeMessage(session); // Fill in header forward.setSubject("Fwd: " + message.getSubject()); forward.setFrom(new InternetAddress(from)); forward.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Create your new message part BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText( "Here you go with the original message:\n\n"); // Create a multi-part to combine the parts Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Create and fill part for the forwarded content messageBodyPart = new MimeBodyPart(); messageBodyPart.setDataHandler(message.getDataHandler()); // Add part to multi part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message forward.setContent(multipart); // Send message Transport.send(forward); Working with attachments Attachments are resources associated with a mail message, usually kept outside of the message like a text file, spreadsheet, or image. As with common mail programs like Eudora and pine, you can attach resources to your mail message with the JavaMail API and get those attachments when you receive the message. Sending attachments: Sending attachments is quite like forwarding messages. You build up the parts to make the complete message. After the first part, your message text, you add other parts where the DataHandler for each is your attachment, instead of the shared handler in the case of a forwarded message. If you are reading the attachment from a file, your attachment data source is a FileDataSource . Reading from a URL, it is a URLDataSource . Once you have your DataSource, just pass it on to the DataHandler constructor, before finally attaching it to the BodyPart with setDataHandler(). Assuming you want to retain the original filename for the attachment, the last thing to do is to set the filename associated with the attachment with the setFileName() method of BodyPart. All this is shown here: // Define message Message message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); message.setSubject("Hello JavaMail Attachment"); // Create the message part BodyPart messageBodyPart = new MimeBodyPart(); // Fill the message messageBodyPart.setText("Pardon Ideas"); Fundamentals of the JavaMail API Page 17 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); // Part two is attachment messageBodyPart = new MimeBodyPart(); DataSource source = new FileDataSource(filename); messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); multipart.addBodyPart(messageBodyPart); // Put parts in message message.setContent(multipart); // Send the message Transport.send(message); When including attachments with your messages, if your program is a servlet, your users must upload the attachment besides telling you where to send the message. Uploading each file can be handled with a form encoding type of multipart/form-data.
Note: Message size is limited by your SMTP server, not the JavaMail API. If you run into problems, consider increasing the Java heap size by setting the ms and mx parameters. Exercise: Exercise 5. How to send attachments on page 28 Getting attachments: Getting attachments out of your messages is a little more involved then sending them because MIME has no simple notion of attachments. The content of your message is a Multipart object when it has attachments. You then need to process each Part, to get the main content and the attachment(s). Parts marked with a disposition of Part.ATTACHMENT from part.getDisposition() are clearly attachments. However, attachments can also come across with no disposition (and a non-text MIME type) or a disposition of Part.INLINE. When the disposition is either Part.ATTACHMENT or Part.INLINE, you can save off the content for that message part. Just get the original filename with getFileName() and the input stream with getInputStream(). Multipart mp = (Multipart)message.getContent(); for (int i=0, n=multipart.getCount(); icom/developerWorks for (int i=0; file.exists(); i++) { file = new File(filename+i); } The code above covers the simplest case where message parts are flagged appropriately. To cover all cases, handle when the disposition is null and get the MIME type of the part to handle accordingly. if (disposition == null) { // Check if plain MimeBodyPart mbp = (MimeBodyPart)part; if (mbp.isMimeType("text/plain")) { // Handle plain } else { // Special non-attachment cases here of image/gif, text/html, ... } ... } Processing HTML messages Sending HTML-based messages can be a little more work than sending plain text message, though it doesn't have to be that much more work. It all depends on your specific requirements. Sending HTML messages: If all you need to do is send the equivalent of an HTML file as the message and let the mail reader worry about fetching any embedded images or related pieces, use the setContent() method of Message, passing along the content as a String and setting the content type to text/html. String htmlText = "

Hello

" + "com/images/logo.gif\">"; message.setContent(htmlText, "text/html")); On the receiving end, if you fetch the message with the JavaMail API, there is nothing built into the API to display the message as HTML. The JavaMail API only sees it as a stream of bytes. To display the message as HTML, you must either use the Swing JEditorPane or some third-party HTML viewer component. if (message.getContentType().equals("text/html")) { String content = (String)message.getContent(); JFrame frame = new JFrame(); JEditorPane text = new JEditorPane("text/html", content); text.setEditable(false); JScrollPane pane = new JScrollPane(text); frame.getContentPane().add(pane); frame.setSize(300, 300); frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); frame.show(); } Including images with your messages: On the other hand, if you want your HTML content message to be complete, with embedded images included as part of the message, you must treat the image as an attachment and reference the image with a special cid URL, where the cid is a reference to the Content-ID header of the image attachment. The process of embedding an image is quite similar to attaching a file to a message, the only Fundamentals of the JavaMail API Page 19 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks difference is you have to tell the MimeMultipart that the parts are related by setting its subtype in the constructor (or with setSubType()) and set the Content-ID header for the image to a random string which is used as the src for the image in the img tag. The following demonstrates this completely. String file = ...; // Create the message Message message = new MimeMessage(session); // Fill its headers message.setSubject("Embedded Image"); message.setFrom(new InternetAddress(from)); message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); // Create your new message part BodyPart messageBodyPart = new MimeBodyPart(); String htmlText = "

Hello

" + ""; messageBodyPart.setContent(htmlText, "text/html"); // Create a related multi-part to combine the parts MimeMultipart multipart = new MimeMultipart("related"); multipart.addBodyPart(messageBodyPart); // Create part for the image messageBodyPart = new MimeBodyPart(); // Fetch the image and associate to part DataSource fds = new FileDataSource(file); messageBodyPart.setDataHandler(new DataHandler(fds)); messageBodyPart.setHeader("Content-ID","memememe"); // Add part to multi-part multipart.addBodyPart(messageBodyPart); // Associate multi-part with message message.setContent(multipart); Exercise: Exercise 6. How to send HTML messages with images on page 29 Fundamentals of the JavaMail API Page 20 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 7. Searching with SearchTerm Introduction The JavaMail API includes a filtering mechanism found in the javax.mail.search package to build up a SearchTerm . Once built, you then ask a Folder what messages match, retrieving an array of Message objects: SearchTerm st = ...; Message[] msgs = folder.search(st); There are 22 different classes available to help you build a search term. * AND terms (class AndTerm) * OR terms (class OrTerm) * NOT terms (class NotTerm) * SENT DATE terms (class SentDateTerm) * CONTENT terms (class BodyTerm) * HEADER terms (FromTerm / FromStringTerm, RecipientTerm / RecipientStringTerm, SubjectTerm, etc..) Essentially, you build up a logical expression for matching messages, then search. For instance the following term searches for messages with a (partial) subject string of ADV or a from field of friend@public.com. You might consider periodically running this query and automatically deleting any messages returned. SearchTerm st = new OrTerm( new SubjectTerm("ADV:"), new FromStringTerm("friend@public.com")); Message[] msgs = folder.search(st); Fundamentals of the JavaMail API Page 21 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 8. Exercises About the exercises These exercises are designed to provide help according to your needs. For example, you might simply complete the exercise given the information and the task list in the exercise body; you might want a few hints; or you may want a step-by-step guide to successfully complete a particular exercise. You can use as much or as little help as you need per exercise. Moreover, because complete solutions are also provided, you can skip a few exercises and still be able to complete future exercises requiring the skipped ones. Each exercise has a list of any prerequisite exercises, a list of skeleton code for you to start with, links to necessary API pages, and a text description of the exercise goal. In addition, there is help for each task and a solutions page with links to files that comprise a solution to the exercise. Exercise 1. How to set up a JavaMail environment In this exercise you will install Sun's JavaMail reference implementation. After installing, you will be introduced to the demonstration programs that come with the reference implementation. Task 1: Download the latest version of the JavaMail API implementation from Sun. Task 2: Download the latest version of the JavaBeans Activation Framework from Sun. Task 3: Unzip the downloaded packages. You get a ZIP file for all platforms for both packages. Help for task 3: You can use the jar tool to unzip the packages. Task 4: Add the mail.jar file from the JavaMail 1.2 download and the activation.jar file from the JavaBeans Activation Framework download to your CLASSPATH. Help for task 4: Copy the files to your extension library directory. For Microsoft Windows, using the default installation copy, the command might look like the following: cd \javamail-1.2 copy mail.jar \jdk1.3\jre\lib\ext cd \jaf-1.0.1 copy activation.jar \jdk1.3\jre\lib\ext If you don't like copying the files to the extension library directory, detailed instructions are available from Sun for setting your CLASSPATH on Windows NT. Task 5: Go into the demo directory that comes with the JavaMail API implementation and compile the msgsend program to send a test message. Help for task 5: javac msgsend.java Fundamentals of the JavaMail API Page 22 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Task 6: Execute the program passing in a from address with the -o option, your SMTP server with the -M option, and the to address (with no option). You'll then enter the subject, the text of your message, and the end-of-file character (CTRL-Z) to signal the end of the message input. Help for task 6: Be sure to replace the from address, SMTP server, and to address. java msgsend -o from@address -M SMTP.Server to@address If you are not sure of your SMTP server, contact your system administrator or check with your Internet Service Provider. Task 7: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 1. How to set up a JavaMail environment: Solution Upon successful completion, the JavaMail reference implementation will be in your CLASSPATH. Exercise 2. How to send your first message In the last exercise you sent a mail message using the demonstration program provided with the JavaMail implementation. In this exercise, you'll create the program yourself. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 1. How to set up a JavaMail environment on page 22 Skeleton code: * MailExample.java Task 1: Starting with the skeleton code , get the system Properties. Help for task 1: Properties props = System.getProperties(); Task 2: Add the name of your SMTP server to the properties for the mail.smtp.host key. Fundamentals of the JavaMail API Page 23 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Help for task 2: props.put("mail.smtp.host", host); Task 3: Get a Session object based on the Properties. Help for task 3: Session session = Session.getDefaultInstance(props, null); Task 4: Create a MimeMessage from the session. Help for task 4: MimeMessage message = new MimeMessage(session); Task 5: Set the from field of the message. Help for task 5: message.setFrom(new InternetAddress(from)); Task 6: Set the to field of the message. Help for task 6: message.addRecipient(Message.RecipientType.TO, new InternetAddress(to)); Task 7: Set the subject of the message. Help for task 7: message.setSubject("Hello JavaMail"); Task 8: Set the content of the message. Help for task 8: message.setText("Welcome to JavaMail"); Task 9: Use a Transport to send the message. Help for task 9: Transport.send(message); Task 10: Compile and run the program, passing your SMTP server, from address, and to address on the command line. Fundamentals of the JavaMail API Page 24 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Help for task 10: java MailExample SMTP.Server from@address to@address Task 11: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 2. How to send your first message: Solution The following Java source file represents a solution to this exercise: * Solution/MailExample.java Exercise 3. How to check for mail In this exercise, create a program that displays the from address and subject for each message and prompts to display the message content. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 1. How to set up a JavaMail environment on page 22 Skeleton Code * GetMessageExample.java Task 1: Starting with the skeleton code , get or create a Properties object. Help for task 1: Properties props = new Properties(); Task 2: Get a Session object based on the Properties. Help for task 2: Session session = Session.getDefaultInstance(props, null); Task 3: Get a Store for your e-mail protocol, either pop3 or imap. Help for task 3: Store store = session.getStore("pop3"); Task 4: Connect to your mail host's store with the appropriate username and password. Fundamentals of the JavaMail API Page 25 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Help for task 4: store.connect(host, username, password); Task 5: Get the folder you want to read. More than likely, this will be the INBOX. Help for task 5: Folder folder = store.getFolder("INBOX"); Task 6: Open the folder read-only. Help for task 6: folder.open(Folder.READ_ONLY); Task 7: Get a directory of the messages in the folder. Save the message list in an array variable named message. Help for task 7: Message message[] = folder.getMessages(); Task 8: For each message, display the from field and the subject. Help for task 8: System.out.println(i + ": " + message[i].getFrom()[0] + "\t" + message[i].getSubject()); Task 9: Display the message content when prompted. Help for task 9: System.out.println(message[i].getContent()); Task 10: Close the connection to the folder and store. Help for task 10: folder.close(false); store.close(); Task 11: Compile and run the program, passing your mail server, username, and password on the command line. Answer YES to the messages you want to read. Just hit ENTER if you don't. If you want to stop reading your mail before making your way through all the messages, enter QUIT. Help for task 11: java GetMessageExample POP.Server username password Fundamentals of the JavaMail API Page 26 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Exercise 3. How to check for mail: Solution The following Java source file represents a solution to this exercise. * Solution/GetMessageExample.java Exercise 4. How to reply to mail In this exercise, create a program that creates a canned reply message and attaches the original message if it's plain text. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 3. How to check for mail on page 25 Skeleton Code: * ReplyExample.java Task 1: The skeleton code already includes the code to get the list of messages from the folder and prompt you to create a reply. Task 2: When answered affirmatively, create a new MimeMessage from the original message. Help for task 2: MimeMessage reply = (MimeMessage)message[i].reply(false); Task 3: Set the from field to your e-mail address. Task 4: Create the text for the reply. Include a canned message to start. When the original message is plain text, add each line of the original message, prefix each line with the "> " characters. Help for task 4: To check for plain text messages, check the messages MIME type with mimeMessage.isMimeType("text/plain"). Task 5: Set the message's content, once the message content is fully determined. Task 6: Send the message. Task 7: Compile and run the program, passing your mail server, SMTP server, username, password, and from address on the command line. Answer YES to the messages you want to send replies. Just hit ENTER if you don't. If you want to stop going through your mail before Fundamentals of the JavaMail API Page 27 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks making your way through all the messages, enter QUIT. Help for task 7: java ReplyExample POP.Server SMTP.Server username password from@address Task 8: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 4. How to reply to mail: Solution The following Java source file represents a solution to this exercise. * Solution/ReplyExample.java Exercise 5. How to send attachments In this exercise, create a program that sends a message with an attachment. For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 2. How to send your first message on page 23 Skeleton Code: * AttachExample.java Task 1: The skeleton code already includes the code to get the initial mail session. Task 2: From the session, get a Message and set its header fields: to, from, and subject. Task 3: Create a BodyPart for the main message content and fill its content with the text of the message. Help for task 3: BodyPart messageBodyPart = new MimeBodyPart(); messageBodyPart.setText("Here's the file"); Task 4: Create a Multipart to combine the main content with the attachment. Add the main content to the multipart. Help for task 4: Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messageBodyPart); Fundamentals of the JavaMail API Page 28 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Task 5: Create a second BodyPart for the attachment. Task 6: Get the attachment as a DataSource. Help for task 6: DataSource source = new FileDataSource(filename); Task 7: Set the DataHandler for the message part to the data source. Carry the original filename along. Help for task 7: messageBodyPart.setDataHandler(new DataHandler(source)); messageBodyPart.setFileName(filename); Task 8: Add the second part of the message to the multipart. Task 9: Set the content of the message to the multipart. Help for task 9: message.setContent(multipart); Task 10: Send the message. Task 11: Compile and run the program, passing your SMTP server, from address, to address, and filename on the command line. This will send the file as an attachment. Help for task 11: java AttachExample SMTP.Server from@address to@address filename Task 12: Check to make sure you received the message with your normal mail reader (Eudora, Outlook Express, pine, ...). Exercise 5. How to send attachments: Solution The following Java source file represents a solution to this exercise. * Solution/AttachExample.java Exercise 6. How to send HTML messages with images In this exercise, create a program that sends an HTML message with an image attachment where the image is displayed within the HTML message. Fundamentals of the JavaMail API Page 29 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks For more help with exercises, see About the exercises on page 22 . Prerequisites: * Exercise 5. How to send attachments on page 28 Skeleton code: * logo.gif * HtmlImageExample.java Task 1: The skeleton code already includes the code to get the initial mail session, create the main message, and fill its headers (to, from, subject). Task 2: Create a BodyPart for the HTML message content. Task 3: Create a text string of the HTML content. Include a reference in the HTML to an image () that is local to the mail message. Help for task 3: Use a cid URL. The content-id will need to be specified for the image later. String htmlText = "

Hello

" + ""; Task 4: Set the content of the message part. Be sure to specify the MIME type is text/html. Help for task 4: messageBodyPart.setContent(htmlText, "text/html"); Task 5: Create a Multipart to combine the main content with the attachment. Be sure to specify that the parts are related. Add the main content to the multipart. Help for task 5: MimeMultipart multipart = new MimeMultipart("related"); multipart.addBodyPart(messageBodyPart); Task 6: Create a second BodyPart for the attachment. Task 7: Get the attachment as a DataSource, and set the DataHandler for the message part to the data source. Task 8: Set the Content-ID header for the part to match the image reference specified in the HTML. Help for task 8: messageBodyPart.setHeader("Content-ID","memememe"); Task 9: Add the second part of the message to the multipart, and set the content of the Fundamentals of the JavaMail API Page 30 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks message to the multipart. Task 10: Send the message. Task 11: Compile and run the program, passing your SMTP server, from address, to address, and filename on the command line. This will send the images as an inline image within the HTML text. Help for task 11: java HtmlImageExample SMTP.Server from@address to@address filename Task 12: Check if your mail reader recognizes the message as HTML and displays the image within the message, instead of as a link to an external attachment file. Help for task 12: If your mail reader can't display HTML messages, consider sending the message to a friend. Exercise 6. How to send HTML messages with images: Solution The following Java source files represent a solution to this exercise. * Solution/logo.gif * Solution/HtmlImageExample.java Fundamentals of the JavaMail API Page 31 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Section 9. Wrapup In summary The JavaMail API is a Java package used for reading, composing, and sending e-mail messages and their attachments. It lets you build standards-based e-mail clients that employ various Internet mail protocols, including SMTP, POP, IMAP, and MIME, as well as related protocols such as NNTP, S/MIME, and others. The API divides naturally into two parts. The first focuses on sending, receiving, and managing messages independent of the protocol used, whereas the second focuses on specific use of the protocols. The purpose of this tutorial was to show how to use the first part of the API, without attempting to deal with protocol providers. The core JavaMail API consists of seven classes --Session, Message, Address, Authenticator, Transport, Store, and Folder --all of which are found in javax.mail, the top-level package for the JavaMail API. We used these classes to work through a number of common e-mail-related tasks, including sending messages, retrieving messages, deleting messages, authenticating, replying to messages, forwarding messages, managing attachments, processing HTML-based messages, and searching or filtering mail lists. Finally, we provided a number of step-by-step exercises to help illustrate the concepts presented. Hopefully, this will help you add e-mail functionality to your platform-independent Java applications. Resources You can do much more with the JavaMail API than what's found here. The lessons and exercises found here can be supplemented by the following resources: * Download the JavaMail 1.2 API from the JavaMail API home page . * The JavaBeans Activation Framework is required for versions 1.2 and 1.1.3 of the JavaMail API. * The JavaMail-interest mailing list is a Sun-hosted discussion forum for developers. * Sun's JavaMail FAQ addresses the use of JavaMail in applets and servlets, as well as prototol-specific questions. * Tutorial author John Zukowski maintains jGuru's JavaMail FAQ . * Want to see how others are using JavaMail? Check out Sun's list of third-party products. * If you want more detail about JavaMail, read Rick Grehan's "How JavaMail keeps it simple" (Lotus Developer Network, June 2000). * Benoit Marchal shows how to use Java and XML to produce plain text and HTML newsletters in this two-part series, "Managing e-zines with JavaMail and XSLT" Part 1 (developerWorks, March 2001) and Part 2 (developerWorks, April 2001). * "Linking Applications with E-mail" (Lotus Developer Network, May 2000) discusses how groupware can facilitate communication, collaboration, and coordination among applications. Fundamentals of the JavaMail API Page 32 Presented by developerWorks, your source for great tutorials ibm.com/developerWorks Feedback Please let us know whether this tutorial was helpful to you and how we could make it better. We'd also like to hear about other tutorial topics you'd like to see covered. Thanks! For questions about the content of this tutorial, contact the author John Zukowski ( jaz@zukowski.net ) Colophon This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorial generator. The Toot-O-Matic tool is a short Java program that uses XSLT stylesheets to convert the XML source into a number of HTML pages, a zip file, JPEG heading graphics, and PDF files. Our ability to generate multiple text and binary formats from a single source file illustrates the power and flexibility of XML. Fundamentals of the JavaMail API Page 33
Table of Contents Header Files The #define Guard Header File Dependencies Inline Functions The -inl.h Files Function Parameter Ordering Names and Order of Includes Scoping Namespaces Nested Classes Nonmember, Static Member, and Global Functions Local Variables Static and Global Variables Classes Doing Work in Constructors Default Constructors Explicit Constructors Copy Constructors Structs vs. Classes Inheritance Multiple Inheritance Interfaces Operator Overloading Access Control Declaration Order Write Short Functions Google-Specific Magic Smart Pointers cpplint Other C++ Features Reference Arguments Function Overloading Default Arguments Variable-Length Arrays and alloca() Friends Exceptions Run-Time Type Information (RTTI) Casting Streams Preincrement and Predecrement Use of const Integer Types 64-bit Portability Preprocessor Macros 0 and NULL sizeof Boost C++0x Naming General Naming Rules File Names Type Names Variable Names Constant Names Function Names Namespace Names Enumerator Names Macro Names Exceptions to Naming Rules Comments Comment Style File Comments Class Comments Function Comments Variable Comments Implementation Comments Punctuation, Spelling and Grammar TODO Comments Deprecation Comments Formatting Line Length Non-ASCII Characters Spaces vs. Tabs Function Declarations and Definitions Function Calls Conditionals Loops and Switch Statements Pointer and Reference Expressions Boolean Expressions Return Values Variable and Array Initialization Preprocessor Directives Class Format Constructor Initializer Lists Namespace Formatting Horizontal Whitespace Vertical Whitespace Exceptions to the Rules Existing Non-conformant Code Windows Code Important Note Displaying Hidden Details in this Guide link ▶This style guide contains many details that are initially hidden from view. They are marked by the triangle icon, which you see here on your left. Click it now. You should see "Hooray" appear below. Hooray! Now you know you can expand points to get more details. Alternatively, there's an "expand all" at the top of this document. Background C++ is the main development language used by many of Google's open-source projects. As every C++ programmer knows, the language has many powerful features, but this power brings with it complexity, which in turn can make code more bug-prone and harder to read and maintain. The goal of this guide is to manage this complexity by describing in detail the dos and don'ts of writing C++ code. These rules exist to keep the code base manageable while still allowing coders to use C++ language features productively. Style, also known as readability, is what we call the conventions that govern our C++ code. The term Style is a bit of a misnomer, since these conventions cover far more than just source file formatting. One way in which we keep the code base manageable is by enforcing consistency. It is very important that any programmer be able to look at another's code and quickly understand it. Maintaining a uniform style and following conventions means that we can more easily use "pattern-matching" to infer what various symbols are and what invariants are true about them. Creating common, required idioms and patterns makes code much easier to understand. In some cases there might be good arguments for changing certain style rules, but we nonetheless keep things as they are in order to preserve consistency. Another issue this guide addresses is that of C++ feature bloat. C++ is a huge language with many advanced features. In some cases we constrain, or even ban, use of certain features. We do this to keep code simple and to avoid the various common errors and problems that these features can cause. This guide lists these features and explains why their use is restricted. Open-source projects developed by Google conform to the requirements in this guide. Note that this guide is not a C++ tutorial: we assume that the reader is familiar with the language. Header Files In general, every .cc file should have an associated .h file. There are some common exceptions, such as unittests and small .cc files containing just a main() function. Correct use of header files can make a huge difference to the readability, size and performance of your code. The following rules will guide you through the various pitfalls of using header files. The #define Guard link ▶All header files should have #define guards to prevent multiple inclusion. The format of the symbol name should be ___H_. To guarantee uniqueness, they should be based on the full path in a project's source tree. For example, the file foo/src/bar/baz.h in project foo should have the following guard: #ifndef FOO_BAR_BAZ_H_ #define FOO_BAR_BAZ_H_ ... #endif // FOO_BAR_BAZ_H_ Header File Dependencies link ▶Don't use an #include when a forward declaration would suffice. When you include a header file you introduce a dependency that will cause your code to be recompiled whenever the header file changes. If your header file includes other header files, any change to those files will cause any code that includes your header to be recompiled. Therefore, we prefer to minimize includes, particularly includes of header files in other header files. You can significantly minimize the number of header files you need to include in your own header files by using forward declarations. For example, if your header file uses the File class in ways that do not require access to the declaration of the File class, your header file can just forward declare class File; instead of having to #include "file/base/file.h". How can we use a class Foo in a header file without access to its definition? We can declare data members of type Foo* or Foo&. We can declare (but not define) functions with arguments, and/or return values, of type Foo. (One exception is if an argument Foo or const Foo& has a non-explicit, one-argument constructor, in which case we need the full definition to support automatic type conversion.) We can declare static data members of type Foo. This is because static data members are defined outside the class definition. On the other hand, you must include the header file for Foo if your class subclasses Foo or has a data member of type Foo. Sometimes it makes sense to have pointer (or better, scoped_ptr) members instead of object members. However, this complicates code readability and imposes a performance penalty, so avoid doing this transformation if the only purpose is to minimize includes in header files. Of course, .cc files typically do require the definitions of the classes they use, and usually have to include several header files. Note: If you use a symbol Foo in your source file, you should bring in a definition for Foo yourself, either via an #include or via a forward declaration. Do not depend on the symbol being brought in transitively via headers not directly included. One exception is if Foo is used in myfile.cc, it's ok to #include (or forward-declare) Foo in myfile.h, instead of myfile.cc. Inline Functions link ▶Define functions inline only when they are small, say, 10 lines or less. Definition: You can declare functions in a way that allows the compiler to expand them inline rather than calling them through the usual function call mechanism. Pros: Inlining a function can generate more efficient object code, as long as the inlined function is small. Feel free to inline accessors and mutators, and other short, performance-critical functions. Cons: Overuse of inlining can actually make programs slower. Depending on a function's size, inlining it can cause the code size to increase or decrease. Inlining a very small accessor function will usually decrease code size while inlining a very large function can dramatically increase code size. On modern processors smaller code usually runs faster due to better use of the instruction cache. Decision: A decent rule of thumb is to not inline a function if it is more than 10 lines long. Beware of destructors, which are often longer than they appear because of implicit member- and base-destructor calls! Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed). It is important to know that functions are not always inlined even if they are declared as such; for example, virtual and recursive functions are not normally inlined. Usually recursive functions should not be inline. The main reason for making a virtual function inline is to place its definition in the class, either for convenience or to document its behavior, e.g., for accessors and mutators. The -inl.h Files link ▶You may use file names with a -inl.h suffix to define complex inline functions when needed. The definition of an inline function needs to be in a header file, so that the compiler has the definition available for inlining at the call sites. However, implementation code properly belongs in .cc files, and we do not like to have much actual code in .h files unless there is a readability or performance advantage. If an inline function definition is short, with very little, if any, logic in it, you should put the code in your .h file. For example, accessors and mutators should certainly be inside a class definition. More complex inline functions may also be put in a .h file for the convenience of the implementer and callers, though if this makes the .h file too unwieldy you can instead put that code in a separate -inl.h file. This separates the implementation from the class definition, while still allowing the implementation to be included where necessary. Another use of -inl.h files is for definitions of function templates. This can be used to keep your template definitions easy to read. Do not forget that a -inl.h file requires a #define guard just like any other header file. Function Parameter Ordering link ▶When defining a function, parameter order is: inputs, then outputs. Parameters to C/C++ functions are either input to the function, output from the function, or both. Input parameters are usually values or const references, while output and input/output parameters will be non-const pointers. When ordering function parameters, put all input-only parameters before any output parameters. In particular, do not add new parameters to the end of the function just because they are new; place new input-only parameters before the output parameters. This is not a hard-and-fast rule. Parameters that are both input and output (often classes/structs) muddy the waters, and, as always, consistency with related functions may require you to bend the rule. Names and Order of Includes link ▶Use standard order for readability and to avoid hidden dependencies: C library, C++ library, other libraries' .h, your project's .h. All of a project's header files should be listed as descentants of the project's source directory without use of UNIX directory shortcuts . (the current directory) or .. (the parent directory). For example, google-awesome-project/src/base/logging.h should be included as #include "base/logging.h" In dir/foo.cc, whose main purpose is to implement or test the stuff in dir2/foo2.h, order your includes as follows: dir2/foo2.h (preferred location — see details below). C system files. C++ system files. Other libraries' .h files. Your project's .h files. The preferred ordering reduces hidden dependencies. We want every header file to be compilable on its own. The easiest way to achieve this is to make sure that every one of them is the first .h file #included in some .cc. dir/foo.cc and dir2/foo2.h are often in the same directory (e.g. base/basictypes_test.cc and base/basictypes.h), but can be in different directories too. Within each section it is nice to order the includes alphabetically. For example, the includes in google-awesome-project/src/foo/internal/fooserver.cc might look like this: #include "foo/public/fooserver.h" // Preferred location. #include #include #include #include #include "base/basictypes.h" #include "base/commandlineflags.h" #include "foo/public/bar.h" Scoping Namespaces link ▶Unnamed namespaces in .cc files are encouraged. With named namespaces, choose the name based on the project, and possibly its path. Do not use a using-directive. Definition: Namespaces subdivide the global scope into distinct, named scopes, and so are useful for preventing name collisions in the global scope. Pros: Namespaces provide a (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes. For example, if two different projects have a class Foo in the global scope, these symbols may collide at compile time or at runtime. If each project places their code in a namespace, project1::Foo and project2::Foo are now distinct symbols that do not collide. Cons: Namespaces can be confusing, because they provide an additional (hierarchical) axis of naming, in addition to the (also hierarchical) name axis provided by classes. Use of unnamed spaces in header files can easily cause violations of the C++ One Definition Rule (ODR). Decision: Use namespaces according to the policy described below. Unnamed Namespaces Unnamed namespaces are allowed and even encouraged in .cc files, to avoid runtime naming conflicts: namespace { // This is in a .cc file. // The content of a namespace is not indented enum { kUnused, kEOF, kError }; // Commonly used tokens. bool AtEof() { return pos_ == kEOF; } // Uses our namespace's EOF. } // namespace However, file-scope declarations that are associated with a particular class may be declared in that class as types, static data members or static member functions rather than as members of an unnamed namespace. Terminate the unnamed namespace as shown, with a comment // namespace. Do not use unnamed namespaces in .h files. Named Namespaces Named namespaces should be used as follows: Namespaces wrap the entire source file after includes, gflags definitions/declarations, and forward declarations of classes from other namespaces: // In the .h file namespace mynamespace { // All declarations are within the namespace scope. // Notice the lack of indentation. class MyClass { public: ... void Foo(); }; } // namespace mynamespace // In the .cc file namespace mynamespace { // Definition of functions is within scope of the namespace. void MyClass::Foo() { ... } } // namespace mynamespace The typical .cc file might have more complex detail, including the need to reference classes in other namespaces. #include "a.h" DEFINE_bool(someflag, false, "dummy flag"); class C; // Forward declaration of class C in the global namespace. namespace a { class A; } // Forward declaration of a::A. namespace b { ...code for b... // Code goes against the left margin. } // namespace b Do not declare anything in namespace std, not even forward declarations of standard library classes. Declaring entities in namespace std is undefined behavior, i.e., not portable. To declare entities from the standard library, include the appropriate header file. You may not use a using-directive to make all names from a namespace available. // Forbidden -- This pollutes the namespace. using namespace foo; You may use a using-declaration anywhere in a .cc file, and in functions, methods or classes in .h files. // OK in .cc files. // Must be in a function, method or class in .h files. using ::foo::bar; Namespace aliases are allowed anywhere in a .cc file, anywhere inside the named namespace that wraps an entire .h file, and in functions and methods. // Shorten access to some commonly used names in .cc files. namespace fbz = ::foo::bar::baz; // Shorten access to some commonly used names (in a .h file). namespace librarian { // The following alias is available to all files including // this header (in namespace librarian): // alias names should therefore be chosen consistently // within a project. namespace pd_s = ::pipeline_diagnostics::sidetable; inline void my_inline_function() { // namespace alias local to a function (or method). namespace fbz = ::foo::bar::baz; ... } } // namespace librarian Note that an alias in a .h file is visible to everyone #including that file, so public headers (those available outside a project) and headers transitively #included by them, should avoid defining aliases, as part of the general goal of keeping public APIs as small as possible. Nested Classes link ▶Although you may use public nested classes when they are part of an interface, consider a namespace to keep declarations out of the global scope. Definition: A class can define another class within it; this is also called a member class. class Foo { private: // Bar is a member class, nested within Foo. class Bar { ... }; }; Pros: This is useful when the nested (or member) class is only used by the enclosing class; making it a member puts it in the enclosing class scope rather than polluting the outer scope with the class name. Nested classes can be forward declared within the enclosing class and then defined in the .cc file to avoid including the nested class definition in the enclosing class declaration, since the nested class definition is usually only relevant to the implementation. Cons: Nested classes can be forward-declared only within the definition of the enclosing class. Thus, any header file manipulating a Foo::Bar* pointer will have to include the full class declaration for Foo. Decision: Do not make nested classes public unless they are actually part of the interface, e.g., a class that holds a set of options for some method. Nonmember, Static Member, and Global Functions link ▶Prefer nonmember functions within a namespace or static member functions to global functions; use completely global functions rarely. Pros: Nonmember and static member functions can be useful in some situations. Putting nonmember functions in a namespace avoids polluting the global namespace. Cons: Nonmember and static member functions may make more sense as members of a new class, especially if they access external resources or have significant dependencies. Decision: Sometimes it is useful, or even necessary, to define a function not bound to a class instance. Such a function can be either a static member or a nonmember function. Nonmember functions should not depend on external variables, and should nearly always exist in a namespace. Rather than creating classes only to group static member functions which do not share static data, use namespaces instead. Functions defined in the same compilation unit as production classes may introduce unnecessary coupling and link-time dependencies when directly called from other compilation units; static member functions are particularly susceptible to this. Consider extracting a new class, or placing the functions in a namespace possibly in a separate library. If you must define a nonmember function and it is only needed in its .cc file, use an unnamed namespace or static linkage (eg static int Foo() {...}) to limit its scope. Local Variables link ▶Place a function's variables in the narrowest scope possible, and initialize variables in the declaration. C++ allows you to declare variables anywhere in a function. We encourage you to declare them in as local a scope as possible, and as close to the first use as possible. This makes it easier for the reader to find the declaration and see what type the variable is and what it was initialized to. In particular, initialization should be used instead of declaration and assignment, e.g. int i; i = f(); // Bad -- initialization separate from declaration. int j = g(); // Good -- declaration has initialization. Note that gcc implements for (int i = 0; i < 10; ++i) correctly (the scope of i is only the scope of the for loop), so you can then reuse i in another for loop in the same scope. It also correctly scopes declarations in if and while statements, e.g. while (const char* p = strchr(str, '/')) str = p + 1; There is one caveat: if the variable is an object, its constructor is invoked every time it enters scope and is created, and its destructor is invoked every time it goes out of scope. // Inefficient implementation: for (int i = 0; i < 1000000; ++i) { Foo f; // My ctor and dtor get called 1000000 times each. f.DoSomething(i); } It may be more efficient to declare such a variable used in a loop outside that loop: Foo f; // My ctor and dtor get called once each. for (int i = 0; i < 1000000; ++i) { f.DoSomething(i); } Static and Global Variables link ▶Static or global variables of class type are forbidden: they cause hard-to-find bugs due to indeterminate order of construction and destruction. Objects with static storage duration, including global variables, static variables, static class member variables, and function static variables, must be Plain Old Data (POD): only ints, chars, floats, or pointers, or arrays/structs of POD. The order in which class constructors and initializers for static variables are called is only partially specified in C++ and can even change from build to build, which can cause bugs that are difficult to find. Therefore in addition to banning globals of class type, we do not allow static POD variables to be initialized with the result of a function, unless that function (such as getenv(), or getpid()) does not itself depend on any other globals. Likewise, the order in which destructors are called is defined to be the reverse of the order in which the constructors were called. Since constructor order is indeterminate, so is destructor order. For example, at program-end time a static variable might have been destroyed, but code still running -- perhaps in another thread -- tries to access it and fails. Or the destructor for a static 'string' variable might be run prior to the destructor for another variable that contains a reference to that string. As a result we only allow static variables to contain POD data. This rule completely disallows vector (use C arrays instead), or string (use const char []). If you need a static or global variable of a class type, consider initializing a pointer (which will never be freed), from either your main() function or from pthread_once(). Note that this must be a raw pointer, not a "smart" pointer, since the smart pointer's destructor will have the order-of-destructor issue that we are trying to avoid. Classes Classes are the fundamental unit of code in C++. Naturally, we use them extensively. This section lists the main dos and don'ts you should follow when writing a class. Doing Work in Constructors link ▶In general, constructors should merely set member variables to their initial values. Any complex initialization should go in an explicit Init() method. Definition: It is possible to perform initialization in the body of the constructor. Pros: Convenience in typing. No need to worry about whether the class has been initialized or not. Cons: The problems with doing work in constructors are: There is no easy way for constructors to signal errors, short of using exceptions (which are forbidden). If the work fails, we now have an object whose initialization code failed, so it may be an indeterminate state. If the work calls virtual functions, these calls will not get dispatched to the subclass implementations. Future modification to your class can quietly introduce this problem even if your class is not currently subclassed, causing much confusion. If someone creates a global variable of this type (which is against the rules, but still), the constructor code will be called before main(), possibly breaking some implicit assumptions in the constructor code. For instance, gflags will not yet have been initialized. Decision: If your object requires non-trivial initialization, consider having an explicit Init() method. In particular, constructors should not call virtual functions, attempt to raise errors, access potentially uninitialized global variables, etc. Default Constructors link ▶You must define a default constructor if your class defines member variables and has no other constructors. Otherwise the compiler will do it for you, badly. Definition: The default constructor is called when we new a class object with no arguments. It is always called when calling new[] (for arrays). Pros: Initializing structures by default, to hold "impossible" values, makes debugging much easier. Cons: Extra work for you, the code writer. Decision: If your class defines member variables and has no other constructors you must define a default constructor (one that takes no arguments). It should preferably initialize the object in such a way that its internal state is consistent and valid. The reason for this is that if you have no other constructors and do not define a default constructor, the compiler will generate one for you. This compiler generated constructor may not initialize your object sensibly. If your class inherits from an existing class but you add no new member variables, you are not required to have a default constructor. Explicit Constructors link ▶Use the C++ keyword explicit for constructors with one argument. Definition: Normally, if a constructor takes one argument, it can be used as a conversion. For instance, if you define Foo::Foo(string name) and then pass a string to a function that expects a Foo, the constructor will be called to convert the string into a Foo and will pass the Foo to your function for you. This can be convenient but is also a source of trouble when things get converted and new objects created without you meaning them to. Declaring a constructor explicit prevents it from being invoked implicitly as a conversion. Pros: Avoids undesirable conversions. Cons: None. Decision: We require all single argument constructors to be explicit. Always put explicit in front of one-argument constructors in the class definition: explicit Foo(string name); The exception is copy constructors, which, in the rare cases when we allow them, should probably not be explicit. Classes that are intended to be transparent wrappers around other classes are also exceptions. Such exceptions should be clearly marked with comments. Copy Constructors link ▶Provide a copy constructor and assignment operator only when necessary. Otherwise, disable them with DISALLOW_COPY_AND_ASSIGN. Definition: The copy constructor and assignment operator are used to create copies of objects. The copy constructor is implicitly invoked by the compiler in some situations, e.g. passing objects by value. Pros: Copy constructors make it easy to copy objects. STL containers require that all contents be copyable and assignable. Copy constructors can be more efficient than CopyFrom()-style workarounds because they combine construction with copying, the compiler can elide them in some contexts, and they make it easier to avoid heap allocation. Cons: Implicit copying of objects in C++ is a rich source of bugs and of performance problems. It also reduces readability, as it becomes hard to track which objects are being passed around by value as opposed to by reference, and therefore where changes to an object are reflected. Decision: Few classes need to be copyable. Most should have neither a copy constructor nor an assignment operator. In many situations, a pointer or reference will work just as well as a copied value, with better performance. For example, you can pass function parameters by reference or pointer instead of by value, and you can store pointers rather than objects in an STL container. If your class needs to be copyable, prefer providing a copy method, such as CopyFrom() or Clone(), rather than a copy constructor, because such methods cannot be invoked implicitly. If a copy method is insufficient in your situation (e.g. for performance reasons, or because your class needs to be stored by value in an STL container), provide both a copy constructor and assignment operator. If your class does not need a copy constructor or assignment operator, you must explicitly disable them. To do so, add dummy declarations for the copy constructor and assignment operator in the private: section of your class, but do not provide any corresponding definition (so that any attempt to use them results in a link error). For convenience, a DISALLOW_COPY_AND_ASSIGN macro can be used: // A macro to disallow the copy constructor and operator= functions // This should be used in the private: declarations for a class #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) Then, in class Foo: class Foo { public: Foo(int f); ~Foo(); private: DISALLOW_COPY_AND_ASSIGN(Foo); }; Structs vs. Classes link ▶Use a struct only for passive objects that carry data; everything else is a class. The struct and class keywords behave almost identically in C++. We add our own semantic meanings to each keyword, so you should use the appropriate keyword for the data-type you're defining. structs should be used for passive objects that carry data, and may have associated constants, but lack any functionality other than access/setting the data members. The accessing/setting of fields is done by directly accessing the fields rather than through method invocations. Methods should not provide behavior but should only be used to set up the data members, e.g., constructor, destructor, Initialize(), Reset(), Validate(). If more functionality is required, a class is more appropriate. If in doubt, make it a class. For consistency with STL, you can use struct instead of class for functors and traits. Note that member variables in structs and classes have different naming rules. Inheritance link ▶Composition is often more appropriate than inheritance. When using inheritance, make it public. Definition: When a sub-class inherits from a base class, it includes the definitions of all the data and operations that the parent base class defines. In practice, inheritance is used in two major ways in C++: implementation inheritance, in which actual code is inherited by the child, and interface inheritance, in which only method names are inherited. Pros: Implementation inheritance reduces code size by re-using the base class code as it specializes an existing type. Because inheritance is a compile-time declaration, you and the compiler can understand the operation and detect errors. Interface inheritance can be used to programmatically enforce that a class expose a particular API. Again, the compiler can detect errors, in this case, when a class does not define a necessary method of the API. Cons: For implementation inheritance, because the code implementing a sub-class is spread between the base and the sub-class, it can be more difficult to understand an implementation. The sub-class cannot override functions that are not virtual, so the sub-class cannot change implementation. The base class may also define some data members, so that specifies physical layout of the base class. Decision: All inheritance should be public. If you want to do private inheritance, you should be including an instance of the base class as a member instead. Do not overuse implementation inheritance. Composition is often more appropriate. Try to restrict use of inheritance to the "is-a" case: Bar subclasses Foo if it can reasonably be said that Bar "is a kind of" Foo. Make your destructor virtual if necessary. If your class has virtual methods, its destructor should be virtual. Limit the use of protected to those member functions that might need to be accessed from subclasses. Note that data members should be private. When redefining an inherited virtual function, explicitly declare it virtual in the declaration of the derived class. Rationale: If virtual is omitted, the reader has to check all ancestors of the class in question to determine if the function is virtual or not. Multiple Inheritance link ▶Only very rarely is multiple implementation inheritance actually useful. We allow multiple inheritance only when at most one of the base classes has an implementation; all other base classes must be pure interface classes tagged with the Interface suffix. Definition: Multiple inheritance allows a sub-class to have more than one base class. We distinguish between base classes that are pure interfaces and those that have an implementation. Pros: Multiple implementation inheritance may let you re-use even more code than single inheritance (see Inheritance). Cons: Only very rarely is multiple implementation inheritance actually useful. When multiple implementation inheritance seems like the solution, you can usually find a different, more explicit, and cleaner solution. Decision: Multiple inheritance is allowed only when all superclasses, with the possible exception of the first one, are pure interfaces. In order to ensure that they remain pure interfaces, they must end with the Interface suffix. Note: There is an exception to this rule on Windows. Interfaces link ▶Classes that satisfy certain conditions are allowed, but not required, to end with an Interface suffix. Definition: A class is a pure interface if it meets the following requirements: It has only public pure virtual ("= 0") methods and static methods (but see below for destructor). It may not have non-static data members. It need not have any constructors defined. If a constructor is provided, it must take no arguments and it must be protected. If it is a subclass, it may only be derived from classes that satisfy these conditions and are tagged with the Interface suffix. An interface class can never be directly instantiated because of the pure virtual method(s) it declares. To make sure all implementations of the interface can be destroyed correctly, they must also declare a virtual destructor (in an exception to the first rule, this should not be pure). See Stroustrup, The C++ Programming Language, 3rd edition, section 12.4 for details. Pros: Tagging a class with the Interface suffix lets others know that they must not add implemented methods or non static data members. This is particularly important in the case of multiple inheritance. Additionally, the interface concept is already well-understood by Java programmers. Cons: The Interface suffix lengthens the class name, which can make it harder to read and understand. Also, the interface property may be considered an implementation detail that shouldn't be exposed to clients. Decision: A class may end with Interface only if it meets the above requirements. We do not require the converse, however: classes that meet the above requirements are not required to end with Interface. Operator Overloading link ▶Do not overload operators except in rare, special circumstances. Definition: A class can define that operators such as + and / operate on the class as if it were a built-in type. Pros: Can make code appear more intuitive because a class will behave in the same way as built-in types (such as int). Overloaded operators are more playful names for functions that are less-colorfully named, such as Equals() or Add(). For some template functions to work correctly, you may need to define operators. Cons: While operator overloading can make code more intuitive, it has several drawbacks: It can fool our intuition into thinking that expensive operations are cheap, built-in operations. It is much harder to find the call sites for overloaded operators. Searching for Equals() is much easier than searching for relevant invocations of ==. Some operators work on pointers too, making it easy to introduce bugs. Foo + 4 may do one thing, while &Foo + 4 does something totally different. The compiler does not complain for either of these, making this very hard to debug. Overloading also has surprising ramifications. For instance, if a class overloads unary operator&, it cannot safely be forward-declared. Decision: In general, do not overload operators. The assignment operator (operator=), in particular, is insidious and should be avoided. You can define functions like Equals() and CopyFrom() if you need them. Likewise, avoid the dangerous unary operator& at all costs, if there's any possibility the class might be forward-declared. However, there may be rare cases where you need to overload an operator to interoperate with templates or "standard" C++ classes (such as operator<<(ostream&, const T&) for logging). These are acceptable if fully justified, but you should try to avoid these whenever possible. In particular, do not overload operator== or operator< just so that your class can be used as a key in an STL container; instead, you should create equality and comparison functor types when declaring the container. Some of the STL algorithms do require you to overload operator==, and you may do so in these cases, provided you document why. See also Copy Constructors and Function Overloading. Access Control link ▶Make data members private, and provide access to them through accessor functions as needed (for technical reasons, we allow data members of a test fixture class to be protected when using Google Test). Typically a variable would be called foo_ and the accessor function foo(). You may also want a mutator function set_foo(). Exception: static const data members (typically called kFoo) need not be private. The definitions of accessors are usually inlined in the header file. See also Inheritance and Function Names. Declaration Order link ▶Use the specified order of declarations within a class: public: before private:, methods before data members (variables), etc. Your class definition should start with its public: section, followed by its protected: section and then its private: section. If any of these sections are empty, omit them. Within each section, the declarations generally should be in the following order: Typedefs and Enums Constants (static const data members) Constructors Destructor Methods, including static methods Data Members (except static const data members) Friend declarations should always be in the private section, and the DISALLOW_COPY_AND_ASSIGN macro invocation should be at the end of the private: section. It should be the last thing in the class. See Copy Constructors. Method definitions in the corresponding .cc file should be the same as the declaration order, as much as possible. Do not put large method definitions inline in the class definition. Usually, only trivial or performance-critical, and very short, methods may be defined inline. See Inline Functions for more details. Write Short Functions link ▶Prefer small and focused functions. We recognize that long functions are sometimes appropriate, so no hard limit is placed on functions length. If a function exceeds about 40 lines, think about whether it can be broken up without harming the structure of the program. Even if your long function works perfectly now, someone modifying it in a few months may add new behavior. This could result in bugs that are hard to find. Keeping your functions short and simple makes it easier for other people to read and modify your code. You could find long and complicated functions when working with some code. Do not be intimidated by modifying existing code: if working with such a function proves to be difficult, you find that errors are hard to debug, or you want to use a piece of it in several different contexts, consider breaking up the function into smaller and more manageable pieces. Google-Specific Magic There are various tricks and utilities that we use to make C++ code more robust, and various ways we use C++ that may differ from what you see elsewhere. Smart Pointers link ▶If you actually need pointer semantics, scoped_ptr is great. You should only use std::tr1::shared_ptr under very specific conditions, such as when objects need to be held by STL containers. You should never use auto_ptr. "Smart" pointers are objects that act like pointers but have added semantics. When a scoped_ptr is destroyed, for instance, it deletes the object it's pointing to. shared_ptr is the same way, but implements reference-counting so only the last pointer to an object deletes it. Generally speaking, we prefer that we design code with clear object ownership. The clearest object ownership is obtained by using an object directly as a field or local variable, without using pointers at all. On the other extreme, by their very definition, reference counted pointers are owned by nobody. The problem with this design is that it is easy to create circular references or other strange conditions that cause an object to never be deleted. It is also slow to perform atomic operations every time a value is copied or assigned. Although they are not recommended, reference counted pointers are sometimes the simplest and most elegant way to solve a problem. cpplint link ▶Use cpplint.py to detect style errors. cpplint.py is a tool that reads a source file and identifies many style errors. It is not perfect, and has both false positives and false negatives, but it is still a valuable tool. False positives can be ignored by putting // NOLINT at the end of the line. Some projects have instructions on how to run cpplint.py from their project tools. If the project you are contributing to does not, you can download cpplint.py separately. Other C++ Features Reference Arguments link ▶All parameters passed by reference must be labeled const. Definition: In C, if a function needs to modify a variable, the parameter must use a pointer, eg int foo(int *pval). In C++, the function can alternatively declare a reference parameter: int foo(int &val). Pros: Defining a parameter as reference avoids ugly code like (*pval)++. Necessary for some applications like copy constructors. Makes it clear, unlike with pointers, that NULL is not a possible value. Cons: References can be confusing, as they have value syntax but pointer semantics. Decision: Within function parameter lists all references must be const: void Foo(const string &in, string *out); In fact it is a very strong convention in Google code that input arguments are values or const references while output arguments are pointers. Input parameters may be const pointers, but we never allow non-const reference parameters. One case when you might want an input parameter to be a const pointer is if you want to emphasize that the argument is not copied, so it must exist for the lifetime of the object; it is usually best to document this in comments as well. STL adapters such as bind2nd and mem_fun do not permit reference parameters, so you must declare functions with pointer parameters in these cases, too. Function Overloading link ▶Use overloaded functions (including constructors) only if a reader looking at a call site can get a good idea of what is happening without having to first figure out exactly which overload is being called. Definition: You may write a function that takes a const string& and overload it with another that takes const char*. class MyClass { public: void Analyze(const string &text); void Analyze(const char *text, size_t textlen); }; Pros: Overloading can make code more intuitive by allowing an identically-named function to take different arguments. It may be necessary for templatized code, and it can be convenient for Visitors. Cons: If a function is overloaded by the argument types alone, a reader may have to understand C++'s complex matching rules in order to tell what's going on. Also many people are confused by the semantics of inheritance if a derived class overrides only some of the variants of a function. Decision: If you want to overload a function, consider qualifying the name with some information about the arguments, e.g., AppendString(), AppendInt() rather than just Append(). Default Arguments link ▶We do not allow default function parameters, except in a few uncommon situations explained below. Pros: Often you have a function that uses lots of default values, but occasionally you want to override the defaults. Default parameters allow an easy way to do this without having to define many functions for the rare exceptions. Cons: People often figure out how to use an API by looking at existing code that uses it. Default parameters are more difficult to maintain because copy-and-paste from previous code may not reveal all the parameters. Copy-and-pasting of code segments can cause major problems when the default arguments are not appropriate for the new code. Decision: Except as described below, we require all arguments to be explicitly specified, to force programmers to consider the API and the values they are passing for each argument rather than silently accepting defaults they may not be aware of. One specific exception is when default arguments are used to simulate variable-length argument lists. // Support up to 4 params by using a default empty AlphaNum. string StrCat(const AlphaNum &a, const AlphaNum &b = gEmptyAlphaNum, const AlphaNum &c = gEmptyAlphaNum, const AlphaNum &d = gEmptyAlphaNum); Variable-Length Arrays and alloca() link ▶We do not allow variable-length arrays or alloca(). Pros: Variable-length arrays have natural-looking syntax. Both variable-length arrays and alloca() are very efficient. Cons: Variable-length arrays and alloca are not part of Standard C++. More importantly, they allocate a data-dependent amount of stack space that can trigger difficult-to-find memory overwriting bugs: "It ran fine on my machine, but dies mysteriously in production". Decision: Use a safe allocator instead, such as scoped_ptr/scoped_array. Friends link ▶We allow use of friend classes and functions, within reason. Friends should usually be defined in the same file so that the reader does not have to look in another file to find uses of the private members of a class. A common use of friend is to have a FooBuilder class be a friend of Foo so that it can construct the inner state of Foo correctly, without exposing this state to the world. In some cases it may be useful to make a unittest class a friend of the class it tests. Friends extend, but do not break, the encapsulation boundary of a class. In some cases this is better than making a member public when you want to give only one other class access to it. However, most classes should interact with other classes solely through their public members. Exceptions link ▶We do not use C++ exceptions. Pros: Exceptions allow higher levels of an application to decide how to handle "can't happen" failures in deeply nested functions, without the obscuring and error-prone bookkeeping of error codes. Exceptions are used by most other modern languages. Using them in C++ would make it more consistent with Python, Java, and the C++ that others are familiar with. Some third-party C++ libraries use exceptions, and turning them off internally makes it harder to integrate with those libraries. Exceptions are the only way for a constructor to fail. We can simulate this with a factory function or an Init() method, but these require heap allocation or a new "invalid" state, respectively. Exceptions are really handy in testing frameworks. Cons: When you add a throw statement to an existing function, you must examine all of its transitive callers. Either they must make at least the basic exception safety guarantee, or they must never catch the exception and be happy with the program terminating as a result. For instance, if f() calls g() calls h(), and h throws an exception that f catches, g has to be careful or it may not clean up properly. More generally, exceptions make the control flow of programs difficult to evaluate by looking at code: functions may return in places you don't expect. This causes maintainability and debugging difficulties. You can minimize this cost via some rules on how and where exceptions can be used, but at the cost of more that a developer needs to know and understand. Exception safety requires both RAII and different coding practices. Lots of supporting machinery is needed to make writing correct exception-safe code easy. Further, to avoid requiring readers to understand the entire call graph, exception-safe code must isolate logic that writes to persistent state into a "commit" phase. This will have both benefits and costs (perhaps where you're forced to obfuscate code to isolate the commit). Allowing exceptions would force us to always pay those costs even when they're not worth it. Turning on exceptions adds data to each binary produced, increasing compile time (probably slightly) and possibly increasing address space pressure. The availability of exceptions may encourage developers to throw them when they are not appropriate or recover from them when it's not safe to do so. For example, invalid user input should not cause exceptions to be thrown. We would need to make the style guide even longer to document these restrictions! Decision: On their face, the benefits of using exceptions outweigh the costs, especially in new projects. However, for existing code, the introduction of exceptions has implications on all dependent code. If exceptions can be propagated beyond a new project, it also becomes problematic to integrate the new project into existing exception-free code. Because most existing C++ code at Google is not prepared to deal with exceptions, it is comparatively difficult to adopt new code that generates exceptions. Given that Google's existing code is not exception-tolerant, the costs of using exceptions are somewhat greater than the costs in a new project. The conversion process would be slow and error-prone. We don't believe that the available alternatives to exceptions, such as error codes and assertions, introduce a significant burden. Our advice against using exceptions is not predicated on philosophical or moral grounds, but practical ones. Because we'd like to use our open-source projects at Google and it's difficult to do so if those projects use exceptions, we need to advise against exceptions in Google open-source projects as well. Things would probably be different if we had to do it all over again from scratch. There is an exception to this rule (no pun intended) for Windows code. Run-Time Type Information (RTTI) link ▶We do not use Run Time Type Information (RTTI). Definition: RTTI allows a programmer to query the C++ class of an object at run time. Pros: It is useful in some unittests. For example, it is useful in tests of factory classes where the test has to verify that a newly created object has the expected dynamic type. In rare circumstances, it is useful even outside of tests. Cons: A query of type during run-time typically means a design problem. If you need to know the type of an object at runtime, that is often an indication that you should reconsider the design of your class. Decision: Do not use RTTI, except in unittests. If you find yourself in need of writing code that behaves differently based on the class of an object, consider one of the alternatives to querying the type. Virtual methods are the preferred way of executing different code paths depending on a specific subclass type. This puts the work within the object itself. If the work belongs outside the object and instead in some processing code, consider a double-dispatch solution, such as the Visitor design pattern. This allows a facility outside the object itself to determine the type of class using the built-in type system. If you think you truly cannot use those ideas, you may use RTTI. But think twice about it. :-) Then think twice again. Do not hand-implement an RTTI-like workaround. The arguments against RTTI apply just as much to workarounds like class hierarchies with type tags. Casting link ▶Use C++ casts like static_cast(). Do not use other cast formats like int y = (int)x; or int y = int(x);. Definition: C++ introduced a different cast system from C that distinguishes the types of cast operations. Pros: The problem with C casts is the ambiguity of the operation; sometimes you are doing a conversion (e.g., (int)3.5) and sometimes you are doing a cast (e.g., (int)"hello"); C++ casts avoid this. Additionally C++ casts are more visible when searching for them. Cons: The syntax is nasty. Decision: Do not use C-style casts. Instead, use these C++-style casts. Use static_cast as the equivalent of a C-style cast that does value conversion, or when you need to explicitly up-cast a pointer from a class to its superclass. Use const_cast to remove the const qualifier (see const). Use reinterpret_cast to do unsafe conversions of pointer types to and from integer and other pointer types. Use this only if you know what you are doing and you understand the aliasing issues. Do not use dynamic_cast except in test code. If you need to know type information at runtime in this way outside of a unittest, you probably have a design flaw. Streams link ▶Use streams only for logging. Definition: Streams are a replacement for printf() and scanf(). Pros: With streams, you do not need to know the type of the object you are printing. You do not have problems with format strings not matching the argument list. (Though with gcc, you do not have that problem with printf either.) Streams have automatic constructors and destructors that open and close the relevant files. Cons: Streams make it difficult to do functionality like pread(). Some formatting (particularly the common format string idiom %.*s) is difficult if not impossible to do efficiently using streams without using printf-like hacks. Streams do not support operator reordering (the %1s directive), which is helpful for internationalization. Decision: Do not use streams, except where required by a logging interface. Use printf-like routines instead. There are various pros and cons to using streams, but in this case, as in many other cases, consistency trumps the debate. Do not use streams in your code. Extended Discussion There has been debate on this issue, so this explains the reasoning in greater depth. Recall the Only One Way guiding principle: we want to make sure that whenever we do a certain type of I/O, the code looks the same in all those places. Because of this, we do not want to allow users to decide between using streams or using printf plus Read/Write/etc. Instead, we should settle on one or the other. We made an exception for logging because it is a pretty specialized application, and for historical reasons. Proponents of streams have argued that streams are the obvious choice of the two, but the issue is not actually so clear. For every advantage of streams they point out, there is an equivalent disadvantage. The biggest advantage is that you do not need to know the type of the object to be printing. This is a fair point. But, there is a downside: you can easily use the wrong type, and the compiler will not warn you. It is easy to make this kind of mistake without knowing when using streams. cout << this; // Prints the address cout << *this; // Prints the contents The compiler does not generate an error because << has been overloaded. We discourage overloading for just this reason. Some say printf formatting is ugly and hard to read, but streams are often no better. Consider the following two fragments, both with the same typo. Which is easier to discover? cerr << "Error connecting to '" hostname.first << ":" hostname.second << ": " hostname.first, foo->bar()->hostname.second, strerror(errno)); And so on and so forth for any issue you might bring up. (You could argue, "Things would be better with the right wrappers," but if it is true for one scheme, is it not also true for the other? Also, remember the goal is to make the language smaller, not add yet more machinery that someone has to learn.) Either path would yield different advantages and disadvantages, and there is not a clearly superior solution. The simplicity doctrine mandates we settle on one of them though, and the majority decision was on printf + read/write. Preincrement and Predecrement link ▶Use prefix form (++i) of the increment and decrement operators with iterators and other template objects. Definition: When a variable is incremented (++i or i++) or decremented (--i or i--) and the value of the expression is not used, one must decide whether to preincrement (decrement) or postincrement (decrement). Pros: When the return value is ignored, the "pre" form (++i) is never less efficient than the "post" form (i++), and is often more efficient. This is because post-increment (or decrement) requires a copy of i to be made, which is the value of the expression. If i is an iterator or other non-scalar type, copying i could be expensive. Since the two types of increment behave the same when the value is ignored, why not just always pre-increment? Cons: The tradition developed, in C, of using post-increment when the expression value is not used, especially in for loops. Some find post-increment easier to read, since the "subject" (i) precedes the "verb" (++), just like in English. Decision: For simple scalar (non-object) values there is no reason to prefer one form and we allow either. For iterators and other template types, use pre-increment. Use of const link ▶We strongly recommend that you use const whenever it makes sense to do so. Definition: Declared variables and parameters can be preceded by the keyword const to indicate the variables are not changed (e.g., const int foo). Class functions can have the const qualifier to indicate the function does not change the state of the class member variables (e.g., class Foo { int Bar(char c) const; };). Pros: Easier for people to understand how variables are being used. Allows the compiler to do better type checking, and, conceivably, generate better code. Helps people convince themselves of program correctness because they know the functions they call are limited in how they can modify your variables. Helps people know what functions are safe to use without locks in multi-threaded programs. Cons: const is viral: if you pass a const variable to a function, that function must have const in its prototype (or the variable will need a const_cast). This can be a particular problem when calling library functions. Decision: const variables, data members, methods and arguments add a level of compile-time type checking; it is better to detect errors as soon as possible. Therefore we strongly recommend that you use const whenever it makes sense to do so: If a function does not modify an argument passed by reference or by pointer, that argument should be const. Declare methods to be const whenever possible. Accessors should almost always be const. Other methods should be const if they do not modify any data members, do not call any non-const methods, and do not return a non-const pointer or non-const reference to a data member. Consider making data members const whenever they do not need to be modified after construction. However, do not go crazy with const. Something like const int * const * const x; is likely overkill, even if it accurately describes how const x is. Focus on what's really useful to know: in this case, const int** x is probably sufficient. The mutable keyword is allowed but is unsafe when used with threads, so thread safety should be carefully considered first. Where to put the const Some people favor the form int const *foo to const int* foo. They argue that this is more readable because it's more consistent: it keeps the rule that const always follows the object it's describing. However, this consistency argument doesn't apply in this case, because the "don't go crazy" dictum eliminates most of the uses you'd have to be consistent with. Putting the const first is arguably more readable, since it follows English in putting the "adjective" (const) before the "noun" (int). That said, while we encourage putting const first, we do not require it. But be consistent with the code around you! Integer Types link ▶Of the built-in C++ integer types, the only one used is int. If a program needs a variable of a different size, use a precise-width integer type from , such as int16_t. Definition: C++ does not specify the sizes of its integer types. Typically people assume that short is 16 bits, int is 32 bits, long is 32 bits and long long is 64 bits. Pros: Uniformity of declaration. Cons: The sizes of integral types in C++ can vary based on compiler and architecture. Decision: defines types like int16_t, uint32_t, int64_t, etc. You should always use those in preference to short, unsigned long long and the like, when you need a guarantee on the size of an integer. Of the C integer types, only int should be used. When appropriate, you are welcome to use standard types like size_t and ptrdiff_t. We use int very often, for integers we know are not going to be too big, e.g., loop counters. Use plain old int for such things. You should assume that an int is at least 32 bits, but don't assume that it has more than 32 bits. If you need a 64-bit integer type, use int64_t or uint64_t. For integers we know can be "big", use int64_t. You should not use the unsigned integer types such as uint32_t, unless the quantity you are representing is really a bit pattern rather than a number, or unless you need defined twos-complement overflow. In particular, do not use unsigned types to say a number will never be negative. Instead, use assertions for this. On Unsigned Integers Some people, including some textbook authors, recommend using unsigned types to represent numbers that are never negative. This is intended as a form of self-documentation. However, in C, the advantages of such documentation are outweighed by the real bugs it can introduce. Consider: for (unsigned int i = foo.Length()-1; i >= 0; --i) ... This code will never terminate! Sometimes gcc will notice this bug and warn you, but often it will not. Equally bad bugs can occur when comparing signed and unsigned variables. Basically, C's type-promotion scheme causes unsigned types to behave differently than one might expect. So, document that a variable is non-negative using assertions. Don't use an unsigned type. 64-bit Portability link ▶Code should be 64-bit and 32-bit friendly. Bear in mind problems of printing, comparisons, and structure alignment. printf() specifiers for some types are not cleanly portable between 32-bit and 64-bit systems. C99 defines some portable format specifiers. Unfortunately, MSVC 7.1 does not understand some of these specifiers and the standard is missing a few, so we have to define our own ugly versions in some cases (in the style of the standard include file inttypes.h): // printf macros for size_t, in the style of inttypes.h #ifdef _LP64 #define __PRIS_PREFIX "z" #else #define __PRIS_PREFIX #endif // Use these macros after a % in a printf format string // to get correct 32/64 bit behavior, like this: // size_t size = records.size(); // printf("%"PRIuS"\n", size); #define PRIdS __PRIS_PREFIX "d" #define PRIxS __PRIS_PREFIX "x" #define PRIuS __PRIS_PREFIX "u" #define PRIXS __PRIS_PREFIX "X" #define PRIoS __PRIS_PREFIX "o" Type DO NOT use DO use Notes void * (or any pointer) %lx %p int64_t %qd, %lld %"PRId64" uint64_t %qu, %llu, %llx %"PRIu64", %"PRIx64" size_t %u %"PRIuS", %"PRIxS" C99 specifies %zu ptrdiff_t %d %"PRIdS" C99 specifies %zd Note that the PRI* macros expand to independent strings which are concatenated by the compiler. Hence if you are using a non-constant format string, you need to insert the value of the macro into the format, rather than the name. It is still possible, as usual, to include length specifiers, etc., after the % when using the PRI* macros. So, e.g. printf("x = %30"PRIuS"\n", x) would expand on 32-bit Linux to printf("x = %30" "u" "\n", x), which the compiler will treat as printf("x = %30u\n", x). Remember that sizeof(void *) != sizeof(int). Use intptr_t if you want a pointer-sized integer. You may need to be careful with structure alignments, particularly for structures being stored on disk. Any class/structure with a int64_t/uint64_t member will by default end up being 8-byte aligned on a 64-bit system. If you have such structures being shared on disk between 32-bit and 64-bit code, you will need to ensure that they are packed the same on both architectures. Most compilers offer a way to alter structure alignment. For gcc, you can use __attribute__((packed)). MSVC offers #pragma pack() and __declspec(align()). Use the LL or ULL suffixes a
ICS - Internet Component Suite - V8 - Delphi 7 to RAD Studio 10 Seattle ======================================================================= (Aka FPIETTE's Components) Revised: March 3, 2016 http://www.overbyte.be/ http://wiki.overbyte.be/ Table of content: ----------------- - Legal issues - Donate - Register - Contributions - Latest Versions - Version Control repository - Installation - Available VCL Components - Sample applications - About SSL - Support - Release notes - Midware - Known problems - Special thanks Legal issues: ------------- Copyright (C) 1997-2016 by Fran鏾is PIETTE Rue de Grady 24, 4053 Embourg, Belgium SSL implementation includes code written by Arno Garrels, Berlin, Germany, contact: ICS is freeware. This software is provided 'as-is', without any express or implied warranty. In no event will the author be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented, you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. 4. You must register this software by sending a picture postcard to the author. Use a nice stamp and mention your name, street address, EMail address and any comment you like to say. 5. As this code make use of OpenSSL, your rights are restricted by OpenSSL license as soon as you use any SSL feature. See http://www.openssl.org for details. Donate ------ ICS is freeware. You can use it without paying anything except the registration postcard (see "register" below). But of course donations are welcome. You can send cash (Euro currency or US Dollars) in an envelop to my street address or buy a gift certificate at Amazon in the UK. I will then use it to buy books. Here is the direct URL at Amazon UK (nearest to my home, please don't use another): http://www.amazon.co.uk/exec/obidos/gc-email-order1/ref=g_gc_email/202-6198323-6681414 For more generous amount, contact me by email. Register -------- ICS is freeware. If you use the components, you must register by sending a picture postcard showing the area you live in and some beautiful stamps for my kids who are stamp collectors. Do not use an envelop, I collect USED postcards sent to me. Write on the postcard that it is your ICS registration. Address your card to: Francois PIETTE, rue de Grady 24, 4053 Embourg, Belgium. Don't forget to mention your name, street address, EMail and web site. Contributions: -------------- ICS has been designed by Fran鏾is PIETTE but many other peoples are working on the components and sample programs. The history of changes in each source file list all developers having contributed (When no name is given, the change is by F. Piette). I can't list all contributors here but I want to specially thanks two specially active contributors: - Arno Garrels - Angus Robertson Latest versions: --------------- The latest versions of ICS can be downloaded from the ICS Wiki web site: http://wiki.overbyte.be/wiki/index.php/ICS_Download ICS V5 and V6 are archive releases no longer updated, last supported release was 2007. ICS V7 is a stable release that may still be updated for major bugs, but not for new releases of Delphi, latest it supported was XE3. ICS V8 is the current development release which is held in a public Version Control repository that is zipped each night for easy download. The download page above also includes the OpenSSL binaries needed to support SSL. ICS V8 supports Delphi 64-bit and Mac OS-X projects. Note that latest C++ Builder version supported is XE3 (lack of spare time, sorry). ICS V9 is in early development and is planned to support Android. There are no current plans for ICS for iOS. Version Control repository: --------------------------- svn://svn.overbyte.be/ics or http://svn.overbyte.be:8443/svn/ics (Usercode = ics, password = ics) Installation: ------------- ICS V8 has been designed for Embarcadero Delphi 2009 and up, and C++ Builder 2009 and up, but is fully compatible with Borland Delphi 7 and CodeGear 2006 and 2007. Embarcadero RAD Studio includes Delphi and C++ Builder. http://www.embarcadero.com/ With Delphi XE2 and later, VCL 64-bit Windows targets are supported for Delphi only. Currently FireMonkey is partly supported for Delphi only (there are still a few non-ported components). ICS for Mac OSX is currently experimental. The zip file has sub-directories in it. You must use the WinZip "Use folder names" option to restore this directory tree or you will have problems because the files would not be in their proper subdirectories. Please note most of these directories are differently named to ICS V7 and earlier, to ease support of multiple versions of Delphi and platforms, and to ease location of similar sample projects. Please don't install V8 over an existing V7 installation, it will be a mess of old and new. This is the new V8 sub-directory layout: .\ Info directory .\Install Component packages project groups for all versions .\Packages (was Delphi\Vc32) Delphi (7 and up) and C++Builder (2006 and up) packages projects .\Source (was Delphi\Vc32) ICS Delphi source code built into packages .\Source\Include (was Delphi\Vc32) .inc files (including OverbyteIcsDefs.inc) .\Source\Extras (was Delphi\Vc32) Extra source code not built into packages .\Source\zobj125 (was Delphi\Vc32) ZLIB C OBJ include files .\Lib Unit output directories for all package builds, subdirectories | for 2007+ will be created on building the packages \$(Config) Release / Debug | \$(Platform) Win32 / Win64 / OSX32 | \ D7..XE8, 10 Seattle includes .dcu and .dfm files for Delphi and .obj and .hpp files for C++ Builder .\Samples Delphi Win32/Win64 common source for all demos .\Samples\delphi\BroswerDemo Delphi Win32/Win64 Web Browser sample application (all Delphi versions) .\Samples\delphi\BroswerDemo\Resources Resource file, web pages and movie linked into browser demo .\Samples\delphi\FtpDemos Delphi Win32/Win64 FTP sample applications (all Delphi versions) .\Samples\delphi\MailNewsDemos Delphi Win32/Win64 SMTP, POP3, NNTP sample applications (all Delphi versions) .\Samples\delphi\MiscDemos Delphi Win32/Win64 Miscellaneous applications (all Delphi versions) .\Samples\delphi\OtherDemos Delphi Win32/Win64 DNS, Ping, SNMP, Syslog sample applications (all Delphi versions) .\Samples\delphi\PlatformDemos Delphi FireMonkey and cross-platform samples (Delphi XE2+) .\Samples\delphi\SocketDemos Delphi Win32/Win64 Socket sample applications (all Delphi versions) .\Samples\delphi\sslinternet Delphi Win32/Win64 SSL-enabled sample applications (all Delphi versions) .\Samples\delphi\WebDemos Delphi Win32/Win64 HTTP sample applications (all Delphi versions) .\Samples\delphi\WebDemos\WebAppServerData Directory for WebAppServ demo data files .\Samples\delphi\WebDemos\WebServData Directory for WebServ demo data files .\Samples\cpp\internet C++Builder sample applications .\Samples\cpp\internet\cb2006 C++Builder 2006 projects .\Samples\cpp\internet\cb2007 C++Builder 2007 projects .\Samples\cpp\internet\cb2009 C++Builder 2009 projects .\Samples\cpp\internet\cb2010 C++Builder 2010 projects .\Samples\cpp\internet\cbXE C++Builder XE projects .\Samples\cpp\internet\cbXE2 C++Builder XE2 projects UPGRADING and REINSTALLING Uninstall an existing ICS package (Menu | Component | Install Packages, select the component package and click Remove). Rename the old ICS directory and unzip to a new or empty directory, remove the old path from the library path and add either the new .\Source directory to the library path under Tools | Options |... or the appropriate .\Lib subdirectory according to version, ie .\Lib\Debug\Win32\D2007 for Delphi 2007. The latter has the advantage that the ICS source code won't be recompiled whenever your project is build. Also under Tools | Options |... add the new .\Source directory to the Browsing path. All DELPHI and C++ BUILDER VERSIONS/WIN32 Always upgrade your compiler with the latest update available from Embarcadero. Always update your system with http://windowsupdate.microsoft.com SSL or not SSL? By default the SSL code is compiled into the run-time package and additional SSL- enabled components are installed. In order to not compile the SSL code into the run-time package and to not install the SSL-Enabled components you need to remove the conditional define USE_SSL from both the run-time and design-time package. However if you do not build your applications with run-time packages it is recommended to build the packages with default settings. The SSL code will the be compiled into your applications depending on whether the conditional define USE_SSL is set in the project options or not (this requires having the .\Source directory in either in the library path or in projects Search path). Actual use of SSL in your applications also requires the OpenSSL files LIBEAY32.DLL and SSLEAY32.DLL being available somewhere in the path. Note different DLLs are needed for Win32 and Win64 applications. The ICS distribution includes the latest Win32 OpenSSL files in the .\OpenSSL-Win32 directory and the two main DLLs duplicated in .\Samples\delphi\sslinternet. Other OpenSSL files, including older and Win64, may be downloaded from: http://wiki.overbyte.be/wiki/index.php/ICS_Download INSTALLATION USING THE INSTALL PROJECT GROUPS For each Delphi and C++ Builder version one project group is provided in directory .\Install: Delphi 7 : D7Install.bpg Delphi 2006 : D2006Install.bdsgroup Delphi 2007 : D2007Install.groupproj Delphi 2009 : D2009Install.groupproj Delphi 2010 : D2010Install.groupproj Delphi XE : DXeInstall.groupproj Delphi XE2 : DXe2Install.groupproj // VCL only, no FireMonkey components Delphi XE2 : DXe2InstallVclFmx.groupproj // Both VCL and FireMonkey components Delphi XE3 : DXe3Install.groupproj // VCL only, no FireMonkey components Delphi XE3 : DXe3InstallVclFmx.groupproj // Both VCL and FireMonkey components Delphi XE4 : DXe4Install.groupproj // VCL only, no FireMonkey components Delphi XE4 : DXe4InstallVclFmx.groupproj // Both VCL and FireMonkey components Delphi XE5 : DXe5Install.groupproj // VCL only, no FireMonkey components Delphi XE5 : DXe5InstallVclFmx.groupproj // Both VCL and FireMonkey components Delphi XE6 : DXe6Install.groupproj // VCL only, no FireMonkey components Delphi XE6 : DXe6InstallVclFmx.groupproj // Both VCL and FireMonkey components Delphi XE7 : DXe7Install.groupproj // VCL only, no FireMonkey components Delphi XE7 : DXe7InstallVclFmx.groupproj // Both VCL and FireMonkey components Delphi XE8 : DXe8Install.groupproj // VCL only, no FireMonkey components Delphi XE8 : DXe8InstallVclFmx.groupproj // Both VCL and FireMonkey components Delphi 10 Seattle : D10SInstall.groupproj // VCL only, no FireMonkey components Delphi 10 Seattle : D10SInstallVclFmx.groupproj // Both VCL and FireMonkey components C++ Builder 2006 : CB2006Install.bdsgroup C++ Builder 2007 : CB2007Install.groupproj C++ Builder 2009 : CB2009Install.groupproj C++ Builder 2010 : CB2010Install.groupproj C++ Builder XE : CBXeInstall.groupproj C++ Builder XE2 : CBXe2Install.groupproj // VCL only no FireMonkey components C++ Builder XE2 : CBXe2InstallVclFmx.groupproj // Both VCL and FireMonkey components C++ Builder XE3 : CBXe3InstallVclFmx.groupproj // Both VCL and FireMonkey components 1 - Do a File/Open Project, navigate to the Install directory, select the correct file and open it. The project manager view should now display two package projects, one run-time and one design-time package. The run-time package name contains the "Run" suffix. The design-time package name contains the "Design" suffix. 2 - Select and Build the run-time package (do not install). 3 - Select and Install the design-time package. After a few seconds, you should have a dialog box telling you the package has been installed with a bunch of new components registered in the Tool Palette under "Overbyte ICS" and "Overbyte ICS SSL". Then do a "Save All" and a "Close All". 4 - One package is installed, called 'Overbyte ICS Design-Time Package for Delphi xxx'. 5 - Various directories under .\Samples\delphi\ include samples that illustrate use of all the ICS components, see later. FIREMONKEY CROSS PLATFORM PACKAGES: 1 - For XE2 and later, DXe?Install (where ? is the version) installs VCL components only, while DXe?InstallVclFmx also installs FireMonkey cross platform components (three run time packages). In order to use this feature first uninstall the old design-time package. 2 = Build all three run-time packages for all available platforms (32-bit and 64-bit Windows and Mac OS X) in the order they are listed in project manager. 3 - Next build and install the three design-time packages in the order they are listed in project manager. 4 - Three packages are installed, called: 'Overbyte ICS Common Design-Time Package for Delphi xxx' 'Overbyte ICS FMX Design-Time Package for Delphi xxx' 'Overbyte ICS VCL Design-Time Package for Delphi xxx' Note that the new packaging is still beta/alpha, both package names and included units might change in a future beta drop. The old VCL packages are still there however they do no longer support FireMonkey and of course only one set of packages can be installed in the IDE at the same time, if you want both VCL and FMX install DXe2InstallVclFmx.groupproj only. Currently the XE2 package cache is buggy and should be disabled by adding the -nocache parameter. 5 - The .\Samples\delphi\PlatformDemos\ folder contains FireMonkey sample projects that may all be built with FireMonkey for Mac OS X (and Windows). ALTERNATE INSTALLATION USING THE PACKAGE PROJECT FILES: For each Delphi and C++ Builder version two package project files exist in the .\Packages directory. One run-time and one design-time package project file. The run-time file name contains the "Run" suffix. The design-time file name contains the "Design" suffix. PACKAGE PROJECT FILE NAMES - VCL: Delphi 7 : OverbyteIcsD7Run.dpk, OverbyteIcsD7Design.dpk Delphi 2006 : OverbyteIcsD2006Run.bdsproj, OverbyteIcsD2006Design.bdsproj Delphi 2007 : OverbyteIcsD2007Run.dproj, OverbyteIcsD2007Design.dproj Delphi 2009 : OverbyteIcsD2009Run.dproj, OverbyteIcsD2009Design.dproj Delphi 2010 : OverbyteIcsD2010Run.dproj, OverbyteIcsD2010Design.dproj Delphi XE : OverbyteIcsDXeRun.dproj, OverbyteIcsDXeDesign.dproj Delphi XE2 : OverbyteIcsDXe2Run.dproj, OverbyteIcsDXe2Design.dproj Delphi XE3 : OverbyteIcsDXe3Run.dproj, OverbyteIcsDXe3Design.dproj Delphi XE4 : OverbyteIcsDXe4Run.dproj, OverbyteIcsDXe4Design.dproj Delphi XE5 : OverbyteIcsDXe5Run.dproj, OverbyteIcsDXe5Design.dproj Delphi XE6 : OverbyteIcsDXe6Run.dproj, OverbyteIcsDXe6Design.dproj Delphi XE7 : OverbyteIcsDXe7Run.dproj, OverbyteIcsDXe7Design.dproj Delphi XE8 : OverbyteIcsDXe8Run.dproj, OverbyteIcsDXe8Design.dproj Delphi 10 Seattle : OverbyteIcsD10SRun.dproj, OverbyteIcsD10SDesign.dproj C++ Builder 2006 : OverbyteIcsCB2006Run.bdsproj, OverbyteIcsCB2006Design.bdsproj C++ Builder 2007 : OverbyteIcsCB2007Run.cbproj, OverbyteIcsCB2007Design.cbproj C++ Builder 2009 : OverbyteIcsCB2009Run.cbproj, OverbyteIcsCB2009Design.cbproj C++ Builder 2010 : OverbyteIcsCB2010Run.cbproj, OverbyteIcsCB2010Design.cbproj C++ Builder XE : OverbyteIcsCBXeRun.cbproj, OverbyteIcsCBXeDesign.cbproj C++ Builder XE2 : OverbyteIcsCBXe2Run.cbproj, OverbyteIcsCBXe2Design.cbproj C++ Builder XE3 : OverbyteIcsCBXe3Run.cbproj, OverbyteIcsCBXe3Design.cbproj PACKAGE PROJECT FILE NAMES - FireMonkey and VCL: Delphi XE2 FMX/VCL : IcsCommonDXe2Run.dproj, IcsCommonDXe2Design.dproj Delphi XE2 VCL : IcsVclDXe2Run.dproj, IcsVclDXe2Design.dproj Delphi XE2 FMX : IcsFmxDXe2Run.dproj, IcsFmxDXe2Design.dproj Delphi XE3 FMX/VCL : IcsCommonDXe3Run.dproj, IcsCommonDXe3Design.dproj Delphi XE3 VCL : IcsVclDXe3Run.dproj, IcsVclDXe3Design.dproj Delphi XE3 FMX : IcsFmxDXe3Run.dproj, IcsFmxDXe3Design.dproj Delphi XE4 FMX/VCL : IcsCommonDXe4Run.dproj, IcsCommonDXe4Design.dproj Delphi XE4 VCL : IcsVclDXe4Run.dproj, IcsVclDXe4Design.dproj Delphi XE4 FMX : IcsFmxDXe4Run.dproj, IcsFmxDXe4Design.dproj Delphi XE5 FMX/VCL : IcsCommonDXe5Run.dproj, IcsCommonDXe5Design.dproj Delphi XE5 VCL : IcsVclDXe5Run.dproj, IcsVclDXe5Design.dproj Delphi XE5 FMX : IcsFmxDXe5Run.dproj, IcsFmxDXe5Design.dproj Delphi XE6 FMX/VCL : IcsCommonDXe6Run.dproj, IcsCommonDXe6Design.dproj Delphi XE6 VCL : IcsVclDXe6Run.dproj, IcsVclDXe6Design.dproj Delphi XE6 FMX : IcsFmxDXe6Run.dproj, IcsFmxDXe6Design.dproj Delphi XE7 FMX/VCL : IcsCommonDXe7Run.dproj, IcsCommonDXe7Design.dproj Delphi XE7 VCL : IcsVclDXe7Run.dproj, IcsVclDXe7Design.dproj Delphi XE7 FMX : IcsFmxDXe7Run.dproj, IcsFmxDXe7Design.dproj Delphi XE8 FMX/VCL : IcsCommonDXe8Run.dproj, IcsCommonDXe8Design.dproj Delphi XE8 VCL : IcsVclDXe8Run.dproj, IcsVclDXe8Design.dproj Delphi XE8 FMX : IcsFmxDXe8Run.dproj, IcsFmxDXe8Design.dproj Delphi 10 Seattle FMX/VCL: IcsCommonD10SRun.dproj, IcsCommonD10SDesign.dproj Delphi 10 Seattle VCL : IcsVclD10SRun.dproj, IcsVclD10SDesign.dproj Delphi 10 Seattle FMX : IcsFmxD10SRun.dproj, IcsFmxD10SDesign.dproj C++ Builder XE2 FMX/VCL : IcsCommonCBXe2Run.dproj, IcsCommonDXe2Design.dproj C++ Builder XE2 VCL : IcsVclCBXe2Run.dproj, IcsVclCBXe2Design.dproj C++ Builder XE2 FMX : IcsFmxCBXe2Run.dproj, IcsFmxCBXe2Design.dproj C++ Builder XE3 FMX/VCL : IcsCommonCBXe3Run.dproj, IcsCommonDXe3Design.dproj C++ Builder XE3 VCL : IcsVclCBXe3Run.dproj, IcsVclCBXe3Design.dproj C++ Builder XE3 FMX : IcsFmxCBXe3Run.dproj, IcsFmxCBXe3Design.dproj 1 - Open and Build the run-time package project (do not install!). 2 - Open and Install the design-time package project. (Do a File/Open Project, browse to the .\Packages directory. Select the correct file and open it. Then in the project manager view, right-click on the package, then click on either the Build or Install button.) 3 - For Delphi XE2 and later, a 64-bit run-time package can be built by changing the package target platform to 64-bit Windows. This has the same name as the 32-bit package, so a different package output directory needs to be specified in Tools / Options / Delphi Options for 64-bit Windows. After a few seconds, you should have a dialog box telling you the package has been installed with a bunch of new components registered in the Tool Palette under "Overbyte ICS" and "Overbyte ICS SSL". Then do a "Save All" and a "Close All". DELPHI 2006/WIN32, 2007/WIN32, 2009/WIN32, 2010/WIN32, XE/WIN32: Having installed the package, verify that the appropriate Win32 Library Path (Tools / Options / Delphi Options / Library - Win32 / Library Path) has been added, .\Lib subdirectory according to version, ie .\Lib\Debug\Win32\D2007 for Delphi 2007. If not, add it manually. It is not mandatory to add .\Lib to the global Delphi path, but it will be much easier for you because otherwise you'll have to add it to each project. DELPHI XE2/WIN32, XE3/WIN32, XE4/WIN32, XE5/WIN32, XE6/WIN32, XE7/WIN32, XE8/WIN32, 10 Seattle/WIN32, XE2/WIN64, XE3/WIN64, XE4/WIN64, XE5/WIN64, XE6/WIN64, XE7/WIN64, XE8/WIN64, 10 Seattle/WIN64: Similar to above, but the Library path is specified separately for 32-bit and 64-bit Windows Platforms. DELPHI 7: Add VC32 directory path to your library path (Tools menu / Environment Options / Library / Library Path. Add .\Lib\Debug\Win32\D7 path at the end of the existing path). SAMPLE DELPHI PROJECTS Once the package is installed, you may open the sample projects. The samples are split into several directories according to protocols, most with a project group that can be opened in all versions of Delphi. .\Samples\delphi\BroswerDemo .\Samples\delphi\FtpDemos\FtpDemos.bpg .\Samples\delphi\MailNewsDemos\MailNewsDemos.bpg .\Samples\delphi\MiscDemos\MiscDemos.bpg .\Samples\delphi\OtherDemos\OtherDemos.bpg .\Samples\delphi\PlatformDemos\XSamples.groupproj .\Samples\delphi\SocketDemos\SocketDemos.bpg .\Samples\delphi\sslinternet\SslDemos.bpg .\Samples\delphi\WebDemos\WebDemos.bpg Full details of the sample projects are shown later in this document. You might get some dialog box telling you that resource files are missing (they may not have been included in the zip file to save space) and are recreated by Delphi. It is OK. Any other error message is a problem you should fix. After all resource files have been recreated, you should see in the project manager a group of projects. To compile all samples in the group at once, do Project / Build all projects. This may take a few minutes. Note 1: Delphi may run out of memory if you ask to compile all projects at once. If you have not enough RAM, then compile each project individually. Note 2: Delphi has warnings which triggers a lot of messages for 100% OK code. You can turn those warnings off in the project/ options / Compiler messages and deselecting: "Deprecated symbol", "Platform symbol", "unsafe type", "unsafe code", "unsafe typecast". Those are intended for .NET and Linux portability. You can safely ignore them if you run windows. For you facility, I included a utility SetProjectOptions (source code, you must compile it) in the internet directory. This utility will update project options to disable the warnings. Once the components are all installed, you may open the sample projects each one after the other and compile them. For each project, do file/open and select the dpr file in the internet directory. Then Project/Build All. C++ BUILDER 2006, 2007, 2009, 2010, XE, XE2, XE3: Follow the installation procedure described for Delphi 2006. Just change the project group and package name: use CB2006, CBXe, etc, see above. You can't have Delphi 2006 and CBuilder 2006 packages installed at the same time in the IDE. So when switching from one to the other, be sure to remove the one you don't need. Building the FireMonkey CBXE2InstallVclFmx C++ packages for OSX may trigger an ILINK32 error, this is a bug in C++ Builder reported as QC #103668 the Win32 packages should build without errors. Once the components are all installed, you may open the sample projects each one after the other and compile them. For each project, do file/open and select the dpr file in the internet directory. Then Project/Build All. Projects are located in SAMPLES\CPP\INTERNET\CB2006\ (or CB2006, CBXE, etc) with a project group in each directory, OverbyteIcsCB2006Sam.bdsgroup, OverbyteIcsCBXe2Sam.groupproj, etc. It is likely that for each project, C++ Builder complains about a missing .res file. This is not a problem, C++ Builder will recreate it as needed. They have not been included to save space in the zip file. Once the components are all installed, you may open the sample projects each one after the other and compile them. For each project, do file/open and select the dpr file in the internet directory. Then Project/Build All. NOTES: - You may have an error message, using Delphi or C++ Builder complaining about Font.Charset, OldCreateOrder and other properties. Those are new properties in newer Delphi or C++ Builder versions, newer than the version you use. You can safely ignore those errors because those properties are not used by the components nor sample programs. You may encounter this error at run time. To avoid it, you must open each form at design time and ignore the error. Then recompile. If you don't ignore the error at design time, you'll have it at runtime ! - If you have Delphi or C++ Builder complaining about a file not found, add .\source directory to your library path. - If you are using C++ Builder you may encounter an error at link time such as "Unable to open file MWBCB30.LIB" (or other libs). This is a bug in C++ Builder. To solve it, you can edit project option file (right click in project manager) and remove any reference to the missing libraries. - Don't forget that the C++Builder components are located in .\delphi\vc32 which is object pascal source code (not a problem for C++Builder, just indicate that the *.pas files are displayed when installing). C++Builder will create the *.hpp files. There are some on-line help files in the VC32 directory. Available VCL Components ------------------------ - The following is a list of the files that should be installed in order to properly add all of the available components in this collection: > OverbyteIcsCharsetComboBox.pas Provides easy MIME charset selection > OverbyteIcsDnsQuery DNS lookup component - useful for getting MX records > OverbyteIcsDprUpdFix.pas IDE plugin for Delphi 2009 and 2010 to update old projects > OverbyteIcsEmulVT.pas ANSI terminal emulation in a control > OverbyteIcsFingCli.pas FINGER client protocol - Find information about user > OverbyteIcsFtpCli.pas FTP client protocol - file transfer > OverbyteIcsFtpSrv.pas FTP server protocol - file transfer > OverbyteIcsFtpSrvT.pas FTP server protocol - helpers > OverbyteIcsHttpAppServer.pas HTTP server protocol - used to build advanced web servers > OverbyteIcsHttpProt.pas HTTP client protocol - used by the web > OverbyteIcsHttpSrv.pas HTTP server protocol - used to build web servers > OverbyteIcsLogger.pas A component to log information > OverbyteIcsMimeDec.pas MIME component - decode file attach, use with POP3 > OverbyteIcsMultiProgressBar.pas A segmented progress bar > OverbyteIcsMultipartFtpDownloader.pas FTP client protocol - download one file using simultaneous connections to speedup download > OverbyteIcsMultipartHttpDownloader.pas HTTP client protocol - download one file using simultaneous connections to speedup download > OverbyteIcsNntpCli.pas NNTP client protocol - send and receive newsgroups messages > OverbyteIcsPing.pas ICMP echo protocol - ping a host > OverbyteIcsPop3Prot.pas POP3 client protocol - get mail from mail server > OverbyteIcsReg.pas Register design components > OverbyteIcsSmtpProt.pas SMTP client protocol - send mail to server > OverbyteIcsSmtpSrv.pas SMTP server protocol - receive mail from client > OverbyteIcsSnmpCli.pas SNMP client protocol - network management > OverbyteIcsSnmpMsgs.pas SNMP client protocol - message helper > OverbyteIcsSysLogClient.pas Syslog Client Protocol - receive syslog messages > OverbyteIcsSysLogDefs.pas Syslog Protocol - helpers > OverbyteIcsSysLogServer.pas Syslog Server Protocol - send syslog messages > OverbyteIcsTnCnx.pas TELNET client protocol - terminal emulation protocol > OverbyteIcsTnEmulVT.pas TELNET and ANSI terminal emulation combined > OverbyteIcsTnOptFrm.pas TELNET Client configuration form > OverbyteIcsTnScript.pas TELNET client protocol - with automation > OverbyteIcsWSocket.pas Winsock component - TCP, UDP, DNS,... > OverbyteIcsWSocketE.pas Register procedure and property editor for TWSocket > OverbyteIcsWSocketS.pas Winsock component for building servers > OverbyteIcsWSocketTS.pas Winsock component for building multithreaded servers - The following list support and utilities units: > OverbyteIcsAsn1Utils.pas ASN1 utilities (for TSnmpClient component) > OverbyteIcsAvlTrees.pas Implements a fast cache-like data storage > OverbyteIcsCharsetUtils.pas MIME-charset functions > OverbyteIcsCookies.pas Client Cookie Handling > OverbyteIcsCRC.pas 32 bit CRC computation > OverbyteIcsCsc.pas character set routines > OverbyteIcsDES.pas Implementation of the Data Encryption Standard (DES) > OverbyteIcsDigestAuth.pas HTTP Digest Access Authentication > OverbyteIcsFormDataDecoder.pas Decode a MIME data block as generated by a HTML form > OverbyteIcsHttpCCodZLib.pas Supports GZIP coding for HttpContCod > OverbyteIcsHttpContCod.pas HTTP Content Coding support, uses extra units > OverbyteIcsIcmp.pas ICMP protocol support, used by the PING component > OverbyteIcsIconv.pas Headers for iconv library (LGPL) > OverbyteIcsLIBEAY.pas Delphi encapsulation for LIBEAY32.DLL (OpenSSL) > OverbyteIcsMD4.pas Implementation of the MD4 Message-Digest Algorithm > OverbyteIcsMD5.pas Implementation of the MD5 Message-Digest Algorithm > OverbyteIcsMimeUtil.pas Support routines for MIME standard > OverbyteIcsMLang.pas A few header translations from MS mlang.h > OverbyteIcsNtlmMsgs.pas Client NTLM authentification messages used within HTTP protocol > OverbyteIcsNtlmSsp.pas Server NTLM authentification of user credentials using Windows SSPI > OverbyteIcsOneTimePw.pas One Time Password support functions, used by FTP > OverbyteIcsSHA1.pas Implementation of US Secure Hash Algorithm 1 (SHA1) > OverbyteIcsSocketUtils.pas Cross platform socket utilities for ICS > OverbyteIcsSSLEAY.pas Delphi encapsulation for SSLEAY32.DLL (OpenSSL) > OverbyteIcsSslSessionCache.pas A very fast external SSL-session-cache component > OverbyteIcsSslThrdLock.pas Implementation of OpenSsl thread locking (Windows); > OverbyteIcsSspi.pas A few header translations from MS sspi.h and security.h > OverbyteIcsStreams.pas Fast streams for ICS > OverbyteIcsThreadTimer.pas A custom timer class using custom timer messages from one or more threads > OverbyteIcsTicks64.pas GetTickCount64 support for all versions of Windows > OverbyteIcsTimeList.pas List of items with expiry times, used for WebSessions > OverbyteIcsTypes.pas Common types, mainly for backward compiler compatibility > OverbyteIcsURL.pas Support routines for URL handling > OverbyteIcsUtils.pas Vast number of common utilities, many supporting Unicode for D7/2007 > OverbyteIcsWSockBuf.pas FIFO buffers for TWSocket > OverbyteIcsWebSession.pas Web session support for THttpAppSrv and MidWare > OverbyteIcsWinnls.pas A few header translations for Unicode Normalization in winnls.h > OverbyteIcsWinsock.pas Some Winsock initialisations > OverbyteIcsWndControl.pas A class that encapsulates a windows message queue and a message map > OverbyteIcsZLibDll.pas Zlib support, interface to external zlib.dll functions > OverbyteIcsZlibHigh.pas Zlib support, high level interface for compression and decompression > OverbyteIcsZLibObj.pas Zlib support, interface to zlib linked C OBJ functions FireMonkey Cross Platform Support: ---------------------------------- For Delphi and C++ Builder XE2 and later, FireMonkey Desktop applications are an alternate to VCL Forms applications, supporting cross platforms of Windows 32-bit and 64-bit and Mac OS X (and perhaps other platforms in future). FireMonkey uses different visual components to VCL, while some non-visual components can be used for both VCL and FMX projects, while other components need special versions, such as ICS. Earlier betas of V8 used the conditional define "FMX" which is *no longer required in project options. Instead in your existing ICS FireMonkey app. add either "Ics.Fmx" to the unit scope names in project options or apply the following changes in the uses clause, rename: OverbyteIcsWndControl -> Ics.Fmx.OverbyteIcsWndControl OverbyteIcsWSocket -> Ics.Fmx.OverbyteIcsWSocket OverbyteIcsFtpCli -> Ics.Fmx.OverbyteIcsFtpCli OverbyteIcsFtpSrv -> Ics.Fmx.OverbyteIcsFtpSrv OverbyteIcsHttpProt -> Ics.Fmx.OverbyteIcsHttpProt OverbyteIcsWSocketS -> Ics.Fmx.OverbyteIcsWSocketS OverbyteIcsSmtpProt -> Ics.Fmx.OverbyteIcsSmtpProt.pas OverbyteIcsPop3Prot -> Ics.Fmx.OverbyteIcsPop3Prot.pas OverbyteIcsNntpCli -> Ics.Fmx.OverbyteIcsNntpCli.pas OverbyteIcsPing -> Ics.Fmx.OverbyteIcsPing.pas OverbyteIcsDnsQuery -> Ics.Fmx.OverbyteIcsDnsQuery.pas OverbyteIcsFingCli -> Ics.Fmx.OverbyteIcsFingCli.pas OverbyteIcsSslSessionCache -> Ics.Fmx.OverbyteIcsSslSessionCache.pas OverbyteIcsSslThrdLock -> Ics.Fmx.OverbyteIcsSslThrdLock.pas OverbyteIcsHttpSrv -> Ics.Fmx.OverbyteIcsHttpSrv.pas OverbyteIcsSocketUtils -> Ics.Fmx.OverbyteIcsSocketUtils.pas OverbyteIcsMultipartFtpDownloader -> Ics.Fmx.OverbyteIcsMultipartFtpDownloader.pas OverbyteIcsMultipartHttpDownloader -> Ics.Fmx.OverbyteIcsMultipartHttpDownloader.pas OverbyteIcsHttpAppServer -> Ics.Fmx.OverbyteIcsHttpAppServer.pas OverbyteIcsThreadTimer -> Ics.Fmx.OverbyteIcsThreadTimer.pas OverbyteIcsCharsetComboBox -> Ics.Fmx.OverbyteIcsCharsetComboBox.pas { Demo units } OverbyteIcsWebAppServerCounter -> Ics.Fmx.OverbyteIcsWebAppServerCounter OverbyteIcsWebAppServerMailer -> Ics.Fmx.OverbyteIcsWebAppServerMailer The list above is also the list of units that now have different names in the FireMonkey framework however most of them share the same source file. Dropping a ICS component on the form will add the correct unit name for each framework automatically (don't forget to disable the package cache as described above). Unit OverbyteIcsLibrary.pas has been *deprecated* and ICS IPv8 doesn't use it anymore. If you used it in your own code read the comment in OverbyteIcsLibrary.pas, search for "deprecated". Sample applications: -------------------- With V8, the sample applications are now grouped into directories according to general functionality, to make it easier to compare related samples. Many samples are similar. When searching for something, always look at the date the demos where created. The most recent is always the best code! In the lists below, ACTIVE!! indicates applications that are actively maintained to test and support new functionality in the ICS components. These may not be simplest samples, but are usually the first to try when learning about a component. Delphi Win32/Win64 Web Browser sample application ------------------------------------------------- .\Samples\delphi\BroswerDemo > FrameBrowserIcs.dpr Web Browser using HtmlViewer component - ACTIVE!! Note this sample needs HtmlViewer component installed Delphi Win32/Win64 FTP sample applications ------------------------------------------ .\Samples\delphi\FtpDemos\FtpDemos.bpg - Project group > OverbyteIcsBasFtp.dpr Basic FTP client program > OverbyteIcsConFtp.dpr Basic console mode FTP client > OverbyteIcsFtpAsy.dpr Example of asynchronous FTP client > OverbyteIcsFtpMulti.dpr Demo to do several FTP downloads in parallel to get a list of files > OverbyteIcsFtpMultipartDownload.dpr Demo to FTP download a single large file in several parts in parallel > OverbyteIcsFtpServ.dpr General purpose FTP server, uses TSocketServer - ACTIVE!! > OverbyteIcsFtpThrd.dpr Demo of multithreaded FTP client, see also FTPASY > OverbyteIcsFtpTst.dpr Basic graphical FTP client - ACTIVE!! Delphi Win32/Win64 SMTP, POP3, NNTP sample applications ------------------------------------------------------- .\Samples\delphi\MailNewsDemos\MailNewsDemos.bpg - Project group > OverbyteIcsBasNntp.dpr Basic NNTP client program > OverbyteIcsConPop3.dpr Basic console mode demo for POP3 (mail receive) > OverbyteIcsConSmtp.dpr Basic console mode demo for SMTP (mail send) > OverbyteIcsMailHtml.dpr Example of HTML formatted EMail sending, including embedded images - ACTIVE!! > OverbyteIcsMailRcv.dpr Internet EMail access using POP3 protocol - ACTIVE!! > OverbyteIcsMailSnd.dpr Example of EMail sending using SMTP, including file attach - ACTIVE!! > OverbyteIcsMailSndAsync.dpr Example of parallel EMail sending with multiple connections > OverbyteIcsMimeDemo.dpr Example of EMail decoding (attached files are extracted) - ACTIVE!! > OverbyteIcsNewsReader.dpr Example of TNntpCli component (Send/receive newsgroups) - ACTIVE!! > OverbyteIcsSmtpServer.dpr Internet EMail server using SMTP protocol - ACTIVE!! Delphi Win32/Win64 Miscellaneous applications --------------------------------------------- .\Samples\delphi\MiscDemos\MiscDemos.bpg - Project group > OverbyteIcsBufStrmTst.dpr Test of buffered stream classes > OverbyteIcsCacheTest.dpr Test of TCacheTree class used in TSslAvlSessionCache > OverbyteIcsMD4Test.dpr Test program for MD4 unit > OverbyteIcsMD5File.dpr Example of MD5 unit: computer MD5 checksum for files > OverbyteIcsMD5Test.dpr Test program for MD5 unit > OverbyteIcsOneTimePassword.dpr One Time Password test routines for OverByteIcsOneTimePw unit > OverbyteIcsSHA1Test.dpr Test program for SHA unit > OverbyteIcsThreadTimerDemo.dpr Demo for TIcsThreadTimer > OverbyteIcsTicks64Demo.dpr GetTickCount64 test routines for OverbyteIcsTicks64 unit > OverbyteIcsTimerDemo.dpr Very simple demo for TIcsTimer > OverByteIcsWndControlTest.dpr Test program for windows and threads Delphi Win32/Win64 DNS, Ping, SNMP, Syslog sample applications -------------------------------------------------------------- .\Samples\delphi\OtherDemos\OtherDemos.bpg - Project group > OverbyteIcsBatchDnsLookup.dpr Batch async DNS lookup using DnsLookup (IPv6 and IPv4) > OverbyteIcsConPing.dpr Basic console mode demo for ping component > OverbyteIcsDll1.dpr Demo showing how to use a TWSocket component in a DLL > OverbyteIcsDll2.dpr Demo showing how to use a THttpCli component in a DLL > OverbyteIcsDllTst.dpr Test program calling ICSDLL1 and ICSDLL2 > OverbyteIcsDnsLook.dpr Example of name resolution (IPv6 and IPv4) > OverbyteIcsDnsResolver.dpr Batch async DNS lookup event driven using DnsQuery > OverbyteIcsFinger.dpr Example of TFingerCli component > OverbyteIcsNsLookup.dpr Demo for the DnsQuery component > OverbyteIcsPingTst.dpr Demo for the ping component, includes trace route > OverbyteIcsSnmpCliTst.dpr Demo for SNMP (simple network management protocol) component > OverbyteIcsSysLogClientDemo.dpr Demo for SysLog client component > OverbyteIcsSysLogServerDemo.dpr Demo for SysLog server component Delphi FireMonkey cross-platform samples (Delphi XE2 and later) --------------------------------------------------------------- All these samples may be built for Mac OS X (and Windows). .\Samples\delphi\PlatformDemos\XSamples.groupproj > IcsCliDemo.dproj Example of client for SRVDEMO, IPV4 only > IcsTcpSrvIPv6.dproj Basic server without client forms, event-driven, IPv4/IPV6 > IcsConSmtp.dproj Basic console mode demo for SMTP (mail send) > IcsMailSnd.dproj Example of EMail sending using SMTP, including file attach > IcsMailRcv.dproj Internet EMail access using POP3 protocol > IcsHttpsTst.dproj Example of THttpCli component (GET), show many features > IcsWebServ.dproj Demo of HTTP server, uses TSocketServer > IcsWebAppServ.dproj Advanced HTTP server demo, uses WebServ, adds sessions > IcsFtpTst.dproj Basic graphical FTP client > IcsFtpServ.dproj General purpose FTP server, uses TSocketServer > IcsUdpLstn.dproj UDP listen demo > IcsUdpSend.dproj UDP send demo > IcsBatchDnsLookup.dproj Batch async DNS lookup using DnsLookup (IPv6 and IPv4) > IcsDll1.dproj Demo showing how to use a TWSocket component in a DLL > IcsDll2.dproj Demo showing how to use a THttpCli component in a DLL > IcsDllTst.dproj Test program calling ICSDLL1 and ICSDLL2 > IcsThreadTimerDemo.dproj Very simple demo for TIcsTimer Delphi Win32/Win64 Socket sample applications --------------------------------------------- .\Samples\delphi\SocketDemos\SocketDemos.bpg - Project group > OverbyteIcsBinCliDemo.dpr Client program to receive binary and delimited text data. Works with BinTcpSrv demo. > OverbyteIcsCliDemo.dpr Example of client for SRVDEMO, IPV4 only - ACTIVE!! > OverbyteIcsClient5.dpr Basic client GUI applications > OverbyteIcsClient7.dpr Simple client application demonstrating TWSocket > OverbyteIcsConCli1.dpr Basic client/server console applications > OverbyteIcsConCli2.dpr Basic client/server console applications with thread > OverbyteIcsConSrv1.dpr Basic server application in console mode > OverbyteIcsConUdpLstn.dpr Console application to listen for UDP messages > OverbyteIcsDynCli.dpr Demo of dynamically created TWSocket components > OverbyteIcsMtSrv.dpr Basic server, multi-threaded, see THRDSRV for better code > OverbyteIcsRecv.dpr Simple file receive (server), use with SENDER demo (client) > OverbyteIcsSender.dpr Simple file send (client), use with RECV demo (server) > OverbyteIcsServer5.dpr Basic server GUI applications > OverbyteIcsSocksTst.dpr How to use TWSocket with SOCKS protocol (firewall traversing) > OverbyteIcsSrvDemo.dpr Example of server using a TTable - ACTIVE!! > OverbyteIcsSrvTcp.dpr Basic server without client forms, event-driven > OverbyteIcsSvcTcp.dpr Same as SRVTCP but as an NT/2K/XP service > OverbyteIcsTWSChat.dpr Chat program (both client and server in a single program) > OverbyteIcsTcpSrv.dpr Basic server without client forms, event-driven, IPv4 only - ACTIVE!! > OverbyteIcsTcpSrvIPv6.dpr Basic server without client forms, event-driven, IPv4/IPV6 - ACTIVE!! > OverbyteIcsTelnetClient.dpr Telnet client using a TnEmulVT > OverbyteIcsThrdSrv.dpr Basic multithreaded TCP server, banner sent in main thread > OverbyteIcsThrdSrvV2.dpr Basic multithreaded TCP server, banner sent in worker thread > OverbyteIcsThrdSrvV3.dpr Basic TCP server showing how to use TWSocketThrdServer > OverbyteIcsTnDemo.dpr Telnet client using a TMemo > OverbyteIcsTnSrv.dpr Basic TCP server with client forms, event-driven > OverbyteIcsUdpLstn.dpr UDP listen demo > OverbyteIcsUdpSend.dpr UDP send demo Delphi Win32/Win64 SSL-enabled sample applications -------------------------------------------------- .\Samples\delphi\sslinternet\SslDemos.bpg - Project group > OverbyteIcsHttpsTst.dpr Example of TSslHttpCli component (GET) - ACTIVE!! > OverbyteIcsPemTool.dpr ICS Pem Certificate Tool - Create and import certificates in OpenSLL PEM format > OverbyteIcsSimpleSslCli.dpr Example of simple SSL client using TSslWSocket - ACTIVE!! > OverbyteIcsSimpleSslServer.dpr Example of SSL server using TSslWSocket - ACTIVE!! > OverbyteIcsSslFtpServ.dpr General purpose FTP SSL server, uses TSocketServer - ACTIVE!! > OverbyteIcsSslFtpTst.dpr Basic graphical FTP SSL client - ACTIVE!! > OverbyteIcsSslMailRcv.dpr Internet EMail access using POP3 protocol and SSL - ACTIVE!! > OverbyteIcsSslMailSnd.dpr Example of EMail sending using SMTP and SSL - ACTIVE!! > OverbyteIcsSslNewsRdr.dpr Example of TSslNntpCli component (Send/receive newsgroups) - ACTIVE!! > OverbyteIcsMsVerify.dpr Verify and show an OpenSSL certificate or certificate chain using class TMsCertChainEngine which uses MS crypto API - ACTIVE!! > OverbyteIcsSslSniSrv.dpr Test of Server Name Indication (SNI) in server mode - ACTIVE!! > OverbyteIcsSslWebServ.dpr Demo of HTTPS server, uses TSocketServer - ACTIVE!! > OverbyteIcsSslWebAppServer.dpr Advanced HTTPS server demo, uses WebServ, adds sessions - ACTIVE!! > OverbyteIcsSslSmtpServer.dpr Internet EMail server using SMTP protocol and SSL - ACTIVE!! Delphi Win32/Win64 HTTP sample applications ------------------------------------------- .\Samples\delphi\WebDemos\WebDemos.bpg - Project group > OverbyteIcsConHttp.dpr Basic console mode HTTP client > OverbyteIcsHttpAsp.dpr Example of THttpCli component with cookie (POST to an ASP page) > OverbyteIcsHttpAsy.dpr Example of THttpCli component with multiple async requests (GET) > OverbyteIcsHttpChk.dpr Example of THttpCli to check for valid URL using HEAD request > OverbyteIcsHttpDmo.dpr Simple HTTP client demo with proxy > OverbyteIcsHttpGet.dpr Example of THttpCli component (GET into a file) > OverbyteIcsHttpMultipartDownload.dpr Demo application for TMultipartHttpDownloader to download files using simultaneous connections > OverbyteIcsHttpPg.dpr Example of THttpCli component (POST to CGI script) > OverbyteIcsHttpPost.dpr Example of THttpCli component (POST), work with WebServ sample - ACTIVE!! > OverbyteIcsHttpThrd.dpr Example of THttpCli component (multi-threaded GET) > OverbyteIcsHttpTst.dpr Example of THttpCli component (GET), show many features - ACTIVE!! > OverbyteIcsIsapi.dll Example of FTP client component within an ISAPI extension > OverbyteIcsWebAppServer.dpr Advanced HTTP server demo, uses WebServ, adds sessions - ACTIVE!! > OverbyteIcsWebServ.dpr Demo of HTTP server, uses TSocketServer - ACTIVE!! Two samples are not in the project group since they need extra components installed > OverbyteIcsRestDemo.drp Demo program showing how to use REST API from Google and Yahoo > OverbyteIcsRestJsonDemo.drp Demo program showing how to use REST API from Google Search and JSON Sample Notes ------------ Note 1: Not all samples have been rewritten in C++ for C++ Builder. And those rewritten are frequently much simpler. So C++ Builder user: have a look at the Delphi sample too ! Note 2: Follow "UserMade" link on ICS web site to find more sample programs written by ICS users. As explained in the component installation, you may encounter an error loading a sample application or running it. This may be because the last time I loaded the form, I was using another Delphi or C++ Builder version which has new properties. You can safely ignore messages related to those new properties. They are not used in the samples. (The properties are CharSet, OldCreateOrder and others). You can also encounter error about duplicate resources. You can ignore them safely. If you have those errors, open each form in the IDE, ignore the error then recompile. If you don't open the form in the IDE, you'll get the errors at runtime and your program will abort. When installing a new version, always delete old dcu, obj, dcpil and always recompile everything ! Close everything before recompiling the library or packages. When installing a new version, be sure to unzip it in the same directory tree as the old one or you'll mess both versions. About SSL: ---------- TSslWSocket and TSslWSocketServer component are derived from the standard TWSocket and TWSocketServer component. The SSL code is compiled into the component only if you define USE_SSL symbol to your packages and projects. Just add USE_SSL to the defines in the project or package options and recompile everything. The components make use of LIBEAY32.DLL and SSLEAY32.DLL to handle SSL protocol stuff. The DLLs are dynamically loaded at runtime. It means that the DLLs will only be required at runtime when you first make use of a SSL function. Your applications will run on systems without OpenSSL DLLs as long as you don't call any SSL function. The files may be downloaded from: http://wiki.overbyte.be/wiki/index.php/ICS_Download Most ICS components have their SSL enabled counter part. They work exactly the same way as the regular component except when SSL specific stuff is needed, for example certificates. To support SSL stuff, the SSL-enabled version use some new properties, events and methods. Many sample programs have their SSL-enabled counter part in a separate sources located in SslInternet folder. SSL certificates: To make use of SSL, you frequently need certificates. I provide some demo certificates I built using command line OpenSSL tool. PEM certificates can be opened by a text editor, LF as well as CRLF are allowed as line breaks. CACERT.PEM : A demo certificate for "Example CA" 01CERT.PEM : A demo certificate which is signed by CACERT.PEM 01KEY.PEM : A demo private key for 01CERT.PEM Passphrase is "password". CLIENT.PEM : A demo certificate and private key. Passphrase is "password". SERVER.PEM : A demo certificate and private key. Passphrase is "password". ROOT.PEM : A demo CA certificate. Passphrase is "password". TRUSTEDCABUNDLE.PEM : A demo CA file in PEM format containing multiple well known root CA certificates to be specified in property CA Path of the demo applications. Read the comments included in this file. 6F6359FC.0 : Located in sub directory SslInternet\TrustedCaStore, it's the file CACERT.PEM stored with a hashed file name. Directory TrustedCaStore can be specified in property CA Path of the demo applications. For details about certificate, see the excellent book: "Network security with OpenSSL", O'Reilly, ISBN 10: 0-596-00270-X The SSL demo project OverbyteIcsPemTool may be used to create self signed PEM certificates, certificate requests for commercial use, to convert existing certificates in the Windows Certificate Store to PEM format understood by OpenSSL and to examine PEM certificates. You will find more information in IcsSslHowTo.txt file. Commercial SSL certificates: To avoid browsers giving certificate warning messages, you need to purchase a SSL certificate from one of numerous companies, such as Verisign, Thawte GeoTrust or RapidSSL. Prices vary dramatically and are often cheaper from resellers such as Servertastic than from the main issuing companies. The main purpose of an SSL certificate is to prove the identity of the owner of a web site, ideally the company behind the web site. That usually requires paper work identifying the company is submitted and also proof the domain being protected is owned by that company, it usually also involves telephone calls. Such certificates are usually called fully validated and cost $120 or more each year for a single domain, ie secure.website.com. Wild card certificates cost $350 or more, but protect multiple sub-domains, ie web.website.com as well. Extended Validation certificates cost from $450 a year, and show the company name in green in the address bar. For testing and simple use, instant issued SSL certificates cost from $15 per year and protect a single domain only with automated checking reducing the cost (an email to admin@website.com to prove you receive email for the domain, perhaps a telephone call as well). Note these instant certificates do not include a company name. To buy and install an SSL certificate for use with ICS and OpenSSL follow these steps: 1 - Build the SSL demo project OverbyteIcsPemTool. Take Extras, Create Certificate Requests, fill in the various fields (check other certificates if uncertain, the Common Name is the domain to protect, ie secure.website.com and E-Mail should be an email address at the than domain, ideally admin or administrator, 2048 bits. Click Create, and specify two file names, first for the private key (mykey.pem) then the certificate request file (myreq.pem). The request can also be done using OpenSSL command line arguments, or you can build it into your own application. 2 - Choose you SSL supplier and certificate type, at some point during the ordering process you will be asked for the certificate request, so open the PEM file you saved with a text editor and copy the base64 encoded block starting -BEGIN CERTIFICATE REQUEST- into the web form. It should be decoded and displayed so you check it's correct. The private key is not needed for the certificate to be issued. At this point the validation process starts as mentioned above, which might take hours or weeks to complete. 3 - Eventually the SSL certificate should be issued, either by email or made available to download from the supplier's web site. It should be in X.509 format in a base64 encoded block starting -BEGIN CERTIFICATE- which should be saved as a PEM file (mycert.pem). There should also be an Intermediate CA certificate, with which your new certificate was signed, which should also be saved as a file (mycacert.pem). This may also be downloadable from the supplier as a bundle file and should be common to any certificates they issue, ie RapidSSL_CA_bundle.pem. 4 - The OverbyteIcsPemTool tool has a View PEM button that allows examination of your new PEM files. 5 - The three PEM files now need to be attached to the SslContext component in your application, with properties SslCertFile, SslPrivKeyFile and SslCAFile. The request certificate file has no further use. Support: -------- There is a mailing list to discuss F. Piette's components and applications. To subscribe surf to http://lists.elists.org/mailman/listinfo/twsocket. Do not use an aliased EMail address, use your real EMail address, the one you'll use to post messages. After asking for subscription, you'll receive a confirmation email you must reply to it or you will _not_ be added to the subscriber's list (this is to check for email path and also make sure someone doesn't subscribe you without your consent). Once you have been registered with the mailing list processor, you can send messages to twsocket@elists.org. Every subscriber will receive a copy of your message. I will respond, but anybody is welcome to respond to each other's messages. So every body can share his expertise. There are many other useful mailing lists at http://www.elists.org ! Before asking a question, browse the message archive you can download from the support page on the web site (click the "support" button from main page) and from the mailing list web site http://lists.elists.org/mailman/listinfo/twsocket. Google is also archiving the list with some delay. If you found a bug, please make a short program that reproduces the problem attach it to a message addressed to me. If I can reproduce the problem, I can find a fix ! Do not send exe file but just source code and instructions. Always use the latest version (beta if any) before reporting any bug. You are also encouraged to use the support mailing list to ask for enhancements. You are welcome to post your own code. The support mailing list has sometimes a heavy traffic. If it is too much for you, you can select "digest" mode in which mailing list processor will mail you only one big message per day. To select digest mode goto http://lists.elists.org/mailman/listinfo/twsocket. You can also subscribe to another mailing list called twsocket-announce which will receive only very few messages when major bug fixes or updates are done. The subscription process is the same as for the other mailing list. See above procedure. Release notes ------------- There is no global release notes. Each component and sample has his own history. You can find those histories in the comment in the beginning of each source file. There are also a bunch of useful comments in the source code. You should at least browse the source for the components you are interested in. MidWare ------- If you wants to build client/server applications using TCP/IP protocol, you can do it easily with ICS. But you can do it much more easily using another freeware product from Fran鏾is Piette: MidWare. Available from the same web site http://www.overbyte.be. francois.piette@overbyte.be francois.piette@swing.be http://www.overbyte.be/ http://wiki.overbyte.be/

64,266

社区成员

发帖
与我相关
我的任务
社区描述
C++ 语言相关问题讨论,技术干货分享,前沿动态等
c++ 技术论坛(原bbs)
社区管理员
  • C++ 语言社区
  • encoderlee
  • paschen
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
  1. 请不要发布与C++技术无关的贴子
  2. 请不要发布与技术无关的招聘、广告的帖子
  3. 请尽可能的描述清楚你的问题,如果涉及到代码请尽可能的格式化一下

试试用AI创作助手写篇文章吧